sleep

Hallo,

First sorry if my english's not very clear :S

im writing a little program which emulates the execution of a theoric language we use at college. The program must have a "step by step" mode which shows the state of the vars every iteration. So i show them in a TextArea, and I highlight the instruction i'm executing, to let it be seen i've put a sleep. The problem is that the program waits to be finished to show all the information, instead of showing a line per second as it do through the console. Any ideas?

This is the method i call every iteration if the execution is on step by step mode

private void stepByStep() throws InterruptedException {

Point pto=line(instruction);

ed.Texto.select(pto.x, pto.y);//To show the line im executing

sleep(1000);

ed.Texto.select(0, 0);

monitorizar();

}

private void monitorizar(){ // It writes in de TextArea the state of the vars

String s="";

for (int j=0;j<variables.length;j++){

s=s+"x"+(j+1)+"="+variables[j]+", ";

}

s=s.substring(0,s.length()-2);

ed.Errores.insert(("\n"+s),(ed.Errores.getText()).length());//><-

//It waits to the end of the program to be shown!!!

System.out.println(s);//<<--It's actually shown every second!!! why not the previous line too?

}

[1364 byte] By [hithwena] at [2007-11-27 0:15:26]
# 1

You cannot use sleep in that fashion.

The reason is more complicated (I'll explain in a bit).

But instead, you need to change your GUI code to first show the first thing you want. Then end.

Use SwingTimer to schedule a delayed event 1 second later,

where it will then draw the second thing and schedule for the next thing.

And so on.

--

The reason is that, when you call GUI operations, the GUI operations do not happen immediately.

Instead, they go onto an event queue.

The AWT Event thread will drain this queue and perform the needed operations.

See http://java.sun.com/j2se/1.5.0/docs/api/java/awt/EventQueue.html

So if you sleep (presumably on the AWT thread), you delay the drawing also.

Edit: I know the thread is called "AWT Event Thread", but Swing uses exactly the same queue,

since it is built on top of AWT. Just in case you're wondering.

KathyMcDonnella at 2007-7-11 22:02:15 > top of Java-index,Java Essentials,Java Programming...
# 2
See these tutorials on how to use the Swing timer: http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html http://java.sun.com/products/jfc/tsc/articles/timer/
KathyMcDonnella at 2007-7-11 22:02:15 > top of Java-index,Java Essentials,Java Programming...