When I try to execute this code in a jFrame: It instead of adding a number from 0 to 10 every 100 milliseconds, seems to wait 1 second and add all the numbers at once?
Any help would be greatly appreciated.
public static void wait(int milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 0; i <= 10; i++) {
wait(100);
jTAOut.append("" + i);
}
}
The event listener is always executed on the same thread, the AWT Event Dispatch Thread (EDT). The GUI also redraws on that thread so cannot update until the listener exits.
You should use javax.swing.Timer
in place of Thread.sleep
. Thread.sleep
should rarely be used. Object.wait
is usually more appropriate so that the thread can be woken for other purposes.
(You have overloaded wait
with methods in Object
, which is at best a very odd thing to do.)