Deadlock when using setText on JTextArea in Swing

社会主义新天地 提交于 2019-12-12 11:31:55

问题


I have the following Java Program which one starts in about 50% of all launch attempts. The rest of the time it seams to deadlock in the background without displaying any GUI. I traced the problem to the setText method of the JTextArea Object. Using another Class like JButton works with setText but JTextArea deadlocks. Can anyone explain to me why this is happening and what is wrong with the following code:

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:


your main method must be wrapped into invokeLater or invokeAndWait, that's basic Swing rule to create 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);
        }
    });
}


来源:https://stackoverflow.com/questions/8865800/deadlock-when-using-settext-on-jtextarea-in-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!