I am trying to make this button disable the two other buttons and execute something graphical at the same time. This is the first thing I tried:
public void actionPerformed(ActionEvent arg0) {
reset.setEnabled(false);
switcher.setEnabled(false);
for (int i = 0; i < 10; i++){
a.change();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
So this is the actionperformed method on the button I’m trying to code and switcher and reset are the buttons I’m disabling, and a.change() is supposed to cause a visual effect. When I tried this, the whole program stopped for ten seconds, and then the buttons disabled, with no visual effect during those ten seconds. Then I tried:
public void actionPerformed(ActionEvent arg0) {
reset.setEnabled(false);
switcher.setEnabled(false);
if (!s.isAlive()){
s = new Thread(new Changer());
s.start();
}
else{
s.interrupt();
}
}
Where Changer is:
private static class Changer implements Runnable {
public void run() {
for (int i = 0; i < 10; i++){
a.change();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
}
This worked exactly how I wanted, with the buttons immediately being disabled, followed by the visual effect. Is the reason for this that all of the effects of actionperformed activate upon exiting the function, so the first way, it would ten seconds for actionperformed to end, and the it would do both disables and ten a.change()s at the end? And the second way it resolves after starting s, so the buttons disable, and then s continues and does its effect after actionperformed has ended?
Yes.
There’s a single UI thread managing events and repainting (updating the screen). In your first attempt you put it to sleep. Doing so meant that nothing else was going to happen (in regard to the UI) until it woke up.