Repainting in an special thread?

  • Thread starter =?iso-8859-1?q?J=FCrgen_Gerstacker?=
  • Start date
?

=?iso-8859-1?q?J=FCrgen_Gerstacker?=

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
 
T

Tom Hawtin

Jürgen Gerstacker said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
KetoBurn
Top