Deadlock when using setText in JTextArea in Swing

I have the following Java program that starts with about 50% of all launch attempts. The rest of the time it comes to a standstill in the background without displaying any graphical interface. I traced the problem using the setText method of the JTextArea object. Using another class, such as JButton, works with setText, but at JTextArea dead ends. Can someone 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"); } }); } 

}

+4
source share
1 answer

your main method should be enclosed in invokeLater or invokeAndWait , this is the main Swing rule for creating a 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); } }); } 
+7
source

Source: https://habr.com/ru/post/1391033/


All Articles