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

}

4

1 回答 1

7

您的 main 方法必须包含在invokeLateror中,这是在 EventDispashThread 上invokeAndWait创建 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);
        }
    });
}
于 2012-01-14T22:22:54.093 回答