Hello!
I have a question about the need of a repainting thread.
I have an application with a timer, that is being fired each
millisecond:
Timer timer;
SmfpTimerTask timerTask;
timerTask=new SmfpTimerTask();
timer.schedule(timerTask,0,1);
class SmfpTimerTask extends TimerTask {
public void run() {
calculations...
if (condition) textfield.setText("...");
}
...
}
The code inside the run() function of the timerTask must be very very
quick (<< 1ms).
>From my Windows C++ programming experience I know, that only
PostMessage() and PostMessageThread() functions are allowed within in
TimerCallbacks, for window-altering functions may need some time to
execute (>1 ms).
I can imagine, that textfield.setText() could take longer to execute
depending on certain cirumstances.
In Windows C++ I would write PostMessage(hwnd,WM_SETTEXT,...) to alter
a textfield, because PostMessage returns before finishing the task.
What is the Java-Way to do this? Is the code above safe?
Or is it better to let the textfield.setText() and other repainting
stuff be done in an extra thread?
Thank you, Juergen
Tom Hawtin - 02 Jun 2007 16:53 GMT
> What is the Java-Way to do this? Is the code above safe?
> Or is it better to let the textfield.setText() and other repainting
> stuff be done in an extra thread?
You shouldn't be using Swing components off the Event Dispatch Thread
(EDT) (with a few exceptions, like calling repaint).
Generally what you would do is to call
java.awt.EventQueue.invokeLater/invokeAndWait with the code to update
the GUI.
If the changes are likely to be very rapid, you may want code to
explicitly avoid overwhelming the EDT with updates.
private final JTextField field;
private volatile boolean queued;
private volatile String text;
public void setText(String text) {
this.text = text;
if (!queued) {
queued = true;
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
queued = false;
field.setText(text);
}
}
}
}
(Disclaimer: Not tested or even compiled.)
Tom Hawtin