Reputation: 241
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");
}
});
}
}
Upvotes: 4
Views: 979
Reputation: 109823
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);
}
});
}
Upvotes: 8