0

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);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • You are sleeping in the thread, where your GUI is running (Event Dispatch Thread). You should never do that, as it will freeze the GUI, just like you described. Have a look at [this answer](https://stackoverflow.com/a/14074427/11441011) which goes in more detail and give alternatives on how to avoid this. – maloomeister Jan 20 '21 at 10:23

1 Answers1

0

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.)

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • Thank you for the answer, but even after about an hour of research into the things you mentioned; I still don't get it. Could you perhaps give an example on what you mean? – Juho Turunen Jan 20 '21 at 12:13