有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有下面的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");
        }
    });
}

}


共 (1) 个答案

  1. # 1 楼答案

    您的主方法必须包装到invokeLaterinvokeAndWait中,这是创建Swing GUI on EventDispashThread的基本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);
            }
        });
    }