'Do JButtons really act like this? [closed]
boolean bool1 = true;
boolean bool2 = false;
boolean bool3 = true;
while (bool3) {
while (bool1) {
if (e.GetSource() == button1) {
System.out.println("1");
bool2 = true;
bool1 = false;
} else if (e.getSource() == button2) {
System.out.println("2");
bool2 = true;
bool1 = false;
} else {
return;
}
}
while (bool2) {
if (e.GetSource() == button1) {
System.out.println("1");
bool2 = false;
bool3 = false;
} else if (e.getSource() == button2) {
System.out.println("2");
bool2 = false;
bool3 = false;
} else {
return;
}
}
}
System.out.println("done");
When I click on button1 which is inside the while(bool1) it prints 1, but after that I don't even have enough time to click another button because the button1 inside while(bool2) also prints which leaves me with 2 print statements even if I only clicked 1 button.
Solution 1:[1]
You don't have to put it inside a loop. You usually implement an action listener that gets called when you click.
As you can tell if you put it inside a while it will never go out.
Look at the tutorial
https://docs.oracle.com/javase/tutorial/uiswing/components/button.html
Is something like this:
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
// do something
} else {
}
}
Solution 2:[2]
If you design your program differently, you probably don't need the loop or e.getSource().
Instead, you usually assign an event handler that "does something" (e.g. print a message, or change a state variable) when the button is pressed.
EXAMPLE:
https://www.tutorialspoint.com/swing/swing_jbutton.htm
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Ok Button clicked.");
}
});
In this case, the button's "event handler" is an "Anonymous class" that implements a custom actionPerformed() method.
Ifyou
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | OscarRyz |
| Solution 2 |
