问题
Here is a snippet
kit.insertHTML(doc, doc.getLength(), "Hello", 0, 0, null);
try{
Thread.sleep(1000);
}catch(Exception e){}
I am using HTMLEditorKit()
and HTMLDocument()
as a textbox.
The textbox should show "Hello" then wait one second however, when I try this, It waits one second then puts the word "Hello" which is not what I want.
I am not sure why this happens because I put this in the logical order. If anyone can help me with this, that would be great.
EDIT:
Does anyone know an alternative, so I can use the "delay" sort of effect?
回答1:
Don't ever call Thread.sleep(...) from within the Swing event thread as this will put the event thread itself to sleep. Since this thread is responsible for all Swing painting and user interaction, this will put your application to sleep.
If all you want is a delay in the display, then consider use of a Swing Timer.
If on the other hand your event thread is being compromised by a long-running task, then do the task in the background, using a SwingWorker (as suggested by Guillaume 1+ to him).
回答2:
You are calling sleep
on the EDT (Event Dispatching Thread). You should avoid this situation as indeed, it freezes the UI.
To avoid this situation, use a SwingWorker instead or as suggested by HFOE, use a Swing Timer
回答3:
Thread.sleep
is a long running task. When you a running such a task in the EDT it blocks all repaint requests from being executed. All repaint requests which are pending and which were sent during the sleep phase are queued for future processing.
As a result when the EDT comes out of the sleep
phase it coalesce all such repaint request (if coalescing is enabled which is the default property) into a single repaint which gets executed. If coalescing is not enabled then all queued request are executed serially without any time gap in between. As a result it seems that the UI did not update.
To correct the situation use a SwingTimer
which triggers periodically after specific intervals of time, or a SwingWorker
.
来源:https://stackoverflow.com/questions/10689898/thread-sleep-is-freezing