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

4
我有一个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");
        }
    });
}

}


2
尽量不要使用invokeLater。这种行为可能是由于缺少分派线程,因为您还没有创建任何窗口。当您显示它时,就会创建一个窗口。 - michael nesterenko
谢谢您的评论,现在这个行为对我来说有意义了。 - Christian
1个回答

7

你的主方法必须被包装在invokeLaterinvokeAndWait中,这是创建Swing GUI on EventDispashThread的基本规则。

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);
        }
    });
}

好的,谢谢您的帮助。我是新手,对这个规则不太了解。 - Christian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接