简体   繁体   中英

Dynamically adding text to a JTextArea using Java

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.

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.

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***********
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM