在Swing中的JTextArea上使用setText时出现死锁

Chr*_*ian 4 java concurrency swing deadlock event-dispatch-thread

我有以下Java程序,其中大约50%的启动尝试启动.其余的时间它在后台接缝死锁而不显示任何GUI.我将问题追溯到JTextArea对象的setText方法.使用像JButton这样的另一个类可以使用setText,但是使用JTextArea死锁.任何人都可以向我解释为什么会发生这种情况以及以下代码有什么问题:

public class TestDeadlock extends JPanel {
private JTextArea text;
TestDeadlock(){
    text = new JTextArea("Test");
    add(text);
    updateGui();
}
public static void main(String[] args){
    JFrame window = new JFrame();
    window.setTitle("Deadlock");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.add(new TestDeadlock());
    window.pack();
    window.setVisible(true);
}

public synchronized void updateGui(){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            System.out.println("Here");
            text.setText("Works");
            System.out.println("Not Here");
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

}

mKo*_*bel 7

您的main方法必须包含在invokeLater或者invokeAndWait,这是在EventDispashThread上创建Swing GUI的基本Swing规则

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            JFrame window = new JFrame();
            window.setTitle("Deadlock");
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.add(new TestDeadlock());
            window.pack();
            window.setVisible(true);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)