简体   繁体   中英

Java Swing multi-threaded access to JTextArea

I have a multi-threaded Java Swing application.

Several threads will call the method with writing to JTextArea via textArea.append("something") . Should I wrap it like this:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        textArea.append("something");
    }
});

Or it is just a content updating and Swing will do the correct threading itself?

In general absolutely any updates you do to Swing, and in particular anything that changes the state or layout of a control, should be done from the Swing thread.

In this case you are absolutely right, wrapping each update into an invokeLater is the correct way to do this. You could try updating your own queue or similar but when Swing has already provided just the functionality you need then it makes sense to use it.

See the JTextArea documentation: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html

Where it says

Warning: Swing is not thread safe. For more information see Swing's Threading Policy.

Where it says:

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.

The JTextArea#append method has nothing documented in it saying that it is safe to use from other threads.

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