How to create on code only one JFrame instead of multiples? - java

I've been searching how to limit my jFrame to open only one each time it's clicked but no success aparently. My code is like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
login = true;
InserirCliente tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
login = false;
InserirCliente tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
And there is a JInternalFrame with:
public InserirCliente(boolean login){
initComponents();
if(login){
jPanel1.setVisible(false);
}
else {
}
}
Pretty simple, just testing it all. But how could it be changed to display only the first one and not more then the first as it is beeing clicked? Are there handles so it receives if there are instances of the JInternalFrame already created?

First, make tela_inserir a public/private variable depending on your need:
private InserirCliente tela_inserir;
Now add the following method to your InserirCliente class:
public Boolean checkVisible(){
if(jPanel1 != null){
return jPanel1.isVisible();
}
return false;
}
Now just check if the inner JPanel is null (Not yet created) and not visible when your buttons are pressed:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Only show new panel if i is not already visible:
if (tela_inserir == null && tela_inserir.checkVisible() == false){
login = true;
tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
//Only show new panel if i is not already visible:
if (tela_inserir == null && tela_inserir.checkVisible() == false){
login = false;
InserirCliente tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
}

Related

Making the "Calling method" wait for the "Return" of data

I have 2 classes, one class is a JFrame (MainUIHolder.java) and the other class is a JDialog (EditValuationsDialog.java). MainUIHolder can call EditValuationsDialog on button click event.
Once EditValuationsDialog is open, user can enter data in its fields and press its "Add" button. OK, here is the issue now. Once the user press the "Add" button, the EditValuationsDialog should inform that to the MainUIHolder.
Below is the code.
MainUIHolder
Action edit = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
JTable table = (JTable)e.getSource();
int rowNum = Integer.valueOf(e.getActionCommand());
Object valueAt = table.getModel().getValueAt(rowNum, 0);
EditValuationsDialog edit = new EditValuationsDialog(null,true);
edit.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
edit.setTitle("Edit Valuations");
edit.setClientName(portfolioViewClientName.getText());
edit.setPortfolioType(portfolioViewInvestmentTypeCombo.getSelectedItem().toString());
edit.setPortfolioId(id);
edit.setOngoingValuationsId(Integer.parseInt(String.valueOf(valueAt)));
edit.setLocationRelativeTo(table);
edit.setVisible(true);
//CATCH THE CALL FROM EditValuationsDialog HERE!!!!//
}
};
EditValuationsDialog
//Action Listeners
private class AddBtnAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(someCondition)
{
return String / int to MainUIHolder (See where I want to catch it in MainUIHolder)
}
else
{
do nothing
}
}
}
In my code I have indicated from where the call to MainUIHolder should be generated and in what place I must catch that call in MainUIHolder. How can I do this call back work?
You could...
Add a static method to EditValuationsDialog that shows the dialog, evaluates the results and returns the value you are expecting...
public void actionPerformed(ActionEvent e)
{
int result = EditValuationsDialog.showDialog();
}
public class EditValuationsDialog ... {
//...
private int result = -1;
//...
public int getResult() {
return result;
}
//...
public static int showDialog(Component source, int rowNum, Object valueAt) {
EditValuationsDialog edit = null;
Window parent = SwingUtilities.windowFor(source);
if (parent instanceof Frame) {
edit = new EditValuationsDialog((Frame)parent,true);
} else if (parent instanceof Dialog) {
edit = new EditValuationsDialog((Dialog)parent,true);
} else {
edit = new EditValuationsDialog(null,true);
}
edit.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
edit.setTitle("Edit Valuations");
edit.setClientName(portfolioViewClientName.getText());
edit.setPortfolioType(portfolioViewInvestmentTypeCombo.getSelectedItem().toString());
edit.setPortfolioId(id);
edit.setOngoingValuationsId(Integer.parseInt(String.valueOf(valueAt)));
edit.setLocationRelativeTo(source);
edit.setVisible(true);
return edit.getResult();
}
//...
private class AddBtnAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(someCondition)
{
result = 0;
}
else
{
result = 1;
}
EditValuationsDialog.this.dispose();
}
}
}
Or you could...
Simply evaluate the results of getResult() from the above example directly...
Side note: Because I don't like extending from top level containers like JDialog, I tend to create some of my panels/components with static showDialog methods, thing something along the lines of a login panel for example. It means I could re-use the panel else where, but provides me with the convenience of been able to popup a dialog when I need to. I've also used JOptionPane from time to time to show these panels, but it depends on the complexity of the available actions...
Make the dialog modal (setModal(true)). Then the code after dialog.setVisible(true) is executed after the dialog is closed.
BTW it's better to pass the MainUIHolder JFrame instance as parent of the dialog.
You could add an interface to the EditValuationsDialog something like this:
Interface EditValuationsDialogInterface {
public void onAddClicked(addedVlue);
}
and then add it as such:
edit.setOnAddButtonCallback(new EditValuationsDialogInterface () {
#Override
onAddClicked(addedVlue){
//DO SOMETHING
}
});
in your EditValuationsDialog's add button onclick call add this:
onAddButtonClickedCallback.onAddClicked(retunrValue);
This allows you to have a direct link back to the original calling class.

Trouble with RadioButtons and booleans connection

Well its weird. I am not good with radiobuttons by the way. But I made a JPanel program in netbeans which includes a RadioButton. You enter all this information with JTextFields(no problem) and then lastly I had a JButton which you click the choice you want. Then I have a JButton that takes all the information and outputs this. For the RadioButton, I first entered the usual:
family = new JRadioButton("Family", true);
friend = new JRadioButton("Friend");
relative = new JRadioButton("Relative");
friendFriend = new JRadioButton("Friend of Friend");
ButtonGroup group = new ButtonGroup();
group.add (friend);
group.add (family);
group.add (relative);
group.add (friendFriend);
(I'm not sure if I needed a listner for the RadioButtons or not but my program still seems to "crash" no matter what).
then I had one action listner for the JButton which included all the textfields and radio buttons. But the RadioButton is the issue.
In the action listner I had:
Object source = event.getSource();
if (source == family)
relation1 = true;
else
if (source == friend)
relation2 = true;
else
if(source == relative)
relation3 = true;
else
if(source == friendFriend)
relation4 = true;
Then I made a relation class:
public class Relation {
private boolean arrayFamily, arrayFriend, arrayRelative, arrayFriendFriend;
public Relation(boolean relation1, boolean relation2, boolean relation3,
boolean relation4)
{
this.arrayFamily = relation1;
this.arrayFriend = relation2;
this.arrayRelative = relation3;
this.arrayFriendFriend = relation4;
}
public String relations ()
{
String relationship = null;
if(arrayFamily && !arrayFriend && !arrayRelative && !arrayFriendFriend == true)
{
relationship = "Family";
}
else
if(arrayFriend && !arrayFamily && !arrayRelative &&
!arrayFriendFriend == true)
{
relationship = "Friend";
}
else
if(arrayRelative && !arrayFamily && !arrayFriend &&
!arrayFriendFriend == true)
{
relationship = "Relative";
}
else
if(arrayFriendFriend && !arrayFamily && !arrayFriend &&
!arrayRelative == true)
{
relationship = "Friend of a Friend";
}
return relationship;
}
}
LASTLY back in the action listner, I implementer this class:
Relation relationship = new Relation(relation1, relation2, relation3
, relation4);
String arrayRelation = relationship.relations();
I lastly included arrayRelation in an array but the array worked fine.
My problem is that the output of the array for my RadioButtons keeps reading "null" (most likey because this code: String relationship = null;). I assume this means that none of my if else statements were satisfied and I really dont know why.
Also important to point out is that if I click submit without clicking any radio button (the button stays on "family"), it reads null. If I click a button once it works perfectly reading the string I intended. But if I click another button afterwards and click submit again, the string goes back to "null".
I know its lengthy but I would really appreciate any help because I am lost.
P.S. some parts of my code are repetitive because I was playing around trying to fix the problem.
I suggest you handle your action events separately, for example:
family.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
familyActionPerformed(evt);
}
});
Then implement familyActionPerformed(evt):
private void familyActionPerformed(java.awt.event.ActionEvent evt) {
// every click on family radio button causes the code here to be executed
relation1 = true;
}
Also write an event handler for the button you click, like this:
submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Here test the state of each radio button
relation1 = family.isSelected();
relation2 = friend.isSelected();
relation3 = relative.isSelected();
relation4 = friendFriend.isSelected();
}
MORE EDIT:
Doing what you're doing with NetBeans should be very easy. Here are tutorials that will clear it all up for you:
Tutorial 1
Tutorial 2
I explain the solution again:
Using 'family' button as an example, in your constructor where you have created and initialised your GUI components do this:
JRadioButton family = new JRadioButton();
// do any other thing you want to do to this button and finally..
family.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
familyActionPerformed(evt);
}
});
JButton submit = new JButton("Submit");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
});
Then somewhere create these methods:
private void familyActionPerformed(java.awt.event.ActionEvent evt){
// each time family is selected, you code processes the lines below:
...
}
private void submiteActionPerformed(java.awt.event.ActionEvent evt){
relation1 = family.isSelected();
relation2 = friend.isSelected();
relation3 = relative.isSelected();
relation4 = friendFriend.isSelected();
}
Do something similar for the rest of the RadioButtons.
I think that you're making things way too complex for yourself. If all you want is the String of the JRadioButton pressed, then use the ButtonGroup to get it for you. It can return the ButtonModel of the selected JRadioButton (if any one was selected), and from that you can extract the actionCommand String, although you'll have to remember to set this when you create your JRadioButton.
For example:
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class JRadioExample extends JPanel {
private static final String[] RADIO_TITLES = { "Family", "Friend",
"Relative", "Friend or Relative" };
private ButtonGroup btnGrp = new ButtonGroup();
public JRadioExample() {
for (int i = 0; i < RADIO_TITLES.length; i++) {
JRadioButton rBtn = new JRadioButton(RADIO_TITLES[i]);
rBtn.setActionCommand(RADIO_TITLES[i]); // ***** this is what needs to
// be set
btnGrp.add(rBtn);
add(rBtn);
}
add(new JButton(new BtnAction("Get Chosen Selection")));
}
private class BtnAction extends AbstractAction {
public BtnAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
ButtonModel model = btnGrp.getSelection();
if (model != null) {
String actionCommand = model.getActionCommand();
System.out.println("Selected Button: " + actionCommand);
} else {
System.out.println("No Button Selected");
}
}
}
private static void createAndShowGui() {
JRadioExample mainPanel = new JRadioExample();
JFrame frame = new JFrame("JRadioExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Always on top with Checkbox on Java

Hello all I am trying to make a new software that it gives me modulo of any number I gave. What I want is I put a JCheckBox on my gui and when it's checked the window should be
setAlwaysOnTop(true);
and when deselected
setAlwaysOnTop(false);
Some of my code is
boolean top = false;
Check = new JCheckBox("Always on top");
Check.setLocation(140, 105);
Check.setSize(150, 20);
Check.setSelected(top);
Check.addItemListener(new CheckBoxListener());
add(Check);
setAlwaysOnTop(top);
private class CheckBoxListener implements ItemListener{
public void itemStateChanged(ItemEvent e){
if(e.getSource()==Check){
if(Check.isSelected()){
top = true;
}else{
top = false;
}
}
}
}
setAlwaysOnTop does not observe further state changes to your boolean top. It takes the value of top when it is passed.
In your listener, write:
if(e.getSource() == Check) {
setAlwaysOnTop(Check.isSelected());
}
Change:
public void itemStateChanged(ItemEvent e){
if(e.getSource()==Check){
if(Check.isSelected()){
top = true;
}else{
top = false;
}
}
}
to
public void itemStateChanged(ItemEvent e){
if(e.getSource()==Check){
setAlwaysOnTop(Check.isSelected());
}
}
}
(Also, look into the various LayoutManagers in Java; don't make a GUI with fixed positioning.)

Java: turn-based battle system (with gui)

EDIT (4/3/2017): Sorry, I was a noob back then.
I'm trying to make a turn-based battle system where the player clicks buttons on his turn. But I can't seem to find out how to code it. Below is the code on what I did.
What should happen here is that when I click the attack button(for example) the next turn will be the monster's turn but the playerTurn variable doesn't change when I click the button. playerTurn is always true. Can you help me correct this? It is a turn-based battle system.
public class BattleFrame extends JFrame implements ActionListener, Runnable {
private JButton atkButton = new JButton("Attack");
private JButton runButton = new JButton("Run");
private JButton itemButton = new JButton("Item");
private JButton magicButton = new JButton("Magic");
private JPanel panelButtons = new JPanel();
private Random rand = new Random();
private Boolean playerTurn;
private Thread t;
public BattleFrame() {
setSize(480, 390);
setLayout(null);
// I have not included the code with the setting of the JButtons
initPanel(); // initialize the panel with buttons
setResizable(false);
setVisible(true);
playerTurn = true;
t = new Thread(this);
t.start();
}
// I'm not so familiar with 'synchronized' but I tried it here but it doesn't change anything
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if(src.equals(atkButton) && playerTurn) {
System.out.println("Attack!");
playerTurn = false;
}
else if(src.equals(runButton) && playerTurn) {
System.out.println("Run!");
playerTurn = false;
}
else if(src.equals(itemButton) && playerTurn) {
System.out.println("Item");
playerTurn = false;
}
else if(src.equals(magicButton) && playerTurn) {
System.out.println("Magic");
playerTurn = false;
}
}
public void run() {
while(true) {
if(playerTurn == false) {
System.out.println("Monster's turn!"); // just printing whose turn it is
playerTurn = true;
}
else System.out.println("player's turn!");
}
}
public static void main(String[] args) {
new BattleFrame();
}
}
A Boolean is an object, so gets compared by identity, not value.
assert new Boolean (true) == new Boolean(true);
The above will fail, as the two different Boolean objects are not the same object.
For general use, use the primitive type boolean, not the standard library class Boolean. Cases where you should use Boolean are pretty rare: it's one of those things that exists more for symmetry than any real practical reason. If you do use it, you need to use a.equals(b) not a == b.
For more details, see:
http://www.java-samples.com/showtutorial.php?tutorialid=221

CheckBoxMenuItem and ButtonGroup

There are CheckBoxMenuItems и ButtonGroup. When I set the listener for current CheckBoxMenuItem, the condition is checked and the error is produced in this listener. I have active another CheckBoxMenuItem, and it is not necessary for me, even I will write "return".
Problem is that the method cannot throw exceptions and the class is anonymous.
Here is the code:
mUserMode.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(currentCard == 0) {
return;
}
boolean IsEmptyFields = true, isCheckedAnswers = false;
// check if all fields is fill in ...
endOfCycle: for(Component component: panelForAddingQuesions.getComponents()) {
if(component instanceof JTextField) {
JTextField question = (JTextField)component;
if(question.getText().length() == 0) {
IsEmptyFields = false;
break endOfCycle;
}
}
}
// and if there is one correct answer in every question
// check if all fields is fill in ...
for(Entry<JTextField, ArrayList<JCheckBox>> entrySets: equivalenceOfQuestionFiledsAndItsAnswers.entrySet()) {
isCheckedAnswers = false;
for(JCheckBox checkbox: entrySets.getValue()) {
if(checkbox.isSelected()) {
isCheckedAnswers = true;
}
}
}
if(IsEmptyFields) {
JOptionPane.showMessageDialog(MainActivity.this,
"Error", "Error",
JOptionPane.ERROR_MESSAGE);
}
else if(isCheckedAnswers) {
JOptionPane.showMessageDialog(MainActivity.this,
"Error","Error",
JOptionPane.ERROR_MESSAGE);
}
else {
cardLayout.last(cardPanel);
currentCard = 0;
}
// It doesn't help
//MainActivity.this.mAdminMode.setEnabled(true);
}
});
There is the method(аctionPerformed) in anonymous class. I want on a condition to cancel switching ChechBoxItem of elements i.e. to stop this operation. But as ,anyway , the method аctionPerformed is completed, there will be automatic a switching of checkboxes as it will be notified View. And I need to prevent it directly in a method actionPerformed
You should call MainActivity.this.mAdminMode.setSelected(true);, not setEnabled(true).

Categories

Resources