javaswingjtextareastyleddocument

Java StyledDocument insertString() in a loop


I am currently writing a really simple program using JSwing. There is a JTextArea ("textArea") inside a JScrollPane ("textPane"). I managed to edit texts and stuff in this TextArea with a StyledDocument named doc. However, when I want to insert a string into this document in a while loop, all texts appear at once after the loop ends. The effect I want is to see the texts come up one by one and line by line with the help of Thread.sleep().

Here is my code sample:

while (listening == false && a <= StoryInterface.getDiaNum()) {
    doStoryMode(a, b);
    Thread.sleep(100); 
    if (b == StoryInterface.getNumOfSentence()[a] - 1) {
        b = 1;
        a ++;
    } else {
        b ++;
    }
}

Where doStoryMode(a, b) is a simple method that calls doc.insertString(...). The program is working, but I couldn't see things coming up one by one. I tried to solve this problem by writing textPane.repaint() and textArea.repaint(), but both were unsuccessful. I searched online and somebody said this can be solved by invokeAndWait() method but when I did so, the error message "Cannot call invokeAndWait from the event dispatcher thread" was displayed.

Please help me with this. I am really new to these concepts. Thanks in advance.


Solution

  • I managed to edit texts and stuff in this TextArea with a StyledDocument named "doc".

    A JTextArea doesn't support a StyledDocument. You would need to use a JTextPane if you want styled text.

    Read the section from the Swing tutorial on Text Component Features for more information and examples.

    However, when I want to insert a string into this document in a while loop, all texts appear at once after the loop ends.

    Correct. your code is executing on the Event Dispatch Thread (EDT). The GUI can't repaint itself until the loop have finished executing.

    So to prevent the EDT from blocking, you need to execute your code on a separate Thread. In this case you can use a SwingWorker for your looping code. The worker would then "publish" results on a regular interval.

    Read the section from the Swing tutorial on Concurrency in Swing for more information about the EDT and SwingWorker.