Reputation: 95
I'm trying to add/append text to a JTextArea
dynamically. I tried doing:
for(int i=0;i<10;i++){
jtextArea.append("i="+i);
//some processing code***********
}
Actually all i
values are appending to jtextarea after completion of for
loop. But I want to add i
value to jtextAres as for
loop is progressing. Thanks in advance.
Upvotes: 1
Views: 2392
Reputation: 117665
I am not sure if I understand your question well, but try this code:
for(int i = 0; i < 10; i++)
{
final int x = i;
SwingUtilities.invokeAndWait(new Runnable()
{
@Override
public void run()
{
jtextArea.append("i=" + x);
}
});
//some processing code***********
}
Upvotes: 3
Reputation: 36621
I assume you are doing this on the Event Dispatch Thread and your processing code will block this thread. As a result, the JTextArea
can not get repainted.
You need to get your processing code of the UI thread. The normal suggestion is to use a SwingWorker
, but in this case it might be easier to just use a regular Thread
and use SwingUtilities.invokeLater
to schedule the append
call on the EDT.
Note: I suggest calling append
on the EDT as of JDK1.7 the javadoc of that method no longer states it is thread safe (the 1.6 javadoc still mentions this). But looking at this question shows that even in 1.6 you are probably safer calling it on the EDT.
The Concurrency in Swing tutorial is a good read about this topic.
Upvotes: 3