1

Possible Duplicate:
GUI threading in java

I have been trying to make a text based game and it is going so far, except for this strange bug when using Thread.sleep() and wait() This code should print a message char by char to a JTextArea called console with a delay between each one.

Here is the code with wait()

int i=0;
synchronized(mon) {
    while(i<msg.length())
    {
        console.setText(console.getText()+ msg.charAt(i));
        i++;
        try {
            mon.wait(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
} 

Here is the code with sleep():

int i=0;
    while(i<msg.length())
    {
        console.setText(console.getText()+ msg.charAt(i));
        i++;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

However, when it reaches this code, the program waits msg.length*500ms then prints the whole msg instantly! Help!

Community
  • 1
  • 1
  • 1
    possible duplicate of [GUI threading in java](http://stackoverflow.com/questions/9495360/gui-threading-in-java) and of http://stackoverflow.com/questions/11927167/jtextarea-appending-problems?rq=1, and of many similar questions. – JB Nizet Dec 15 '12 at 21:39

1 Answers1

6

It is the usual problem: YOU SHALL NOT BLOCK THE "EVENT DISPATCH THREAD" (EDT).

The EDT is responsible both for drawing the components and for dispatching events. So when you block this thread then next redraw will happen after you leave you method and give the control back to the EDT.

You have to do your "animation" outside the EDT.

Lookup this site, Google or any Swing tutorial using these keywords and you will get plenty of information.

A.H.
  • 63,967
  • 15
  • 92
  • 126