在Swing中的JTextArea上使用setText时发生死锁 [英] Deadlock when using setText on JTextArea in Swing
问题描述
我有以下Java程序,其中大约50%的启动尝试启动。其余的时间它接缝在后台死锁,没有显示任何GUI。我跟踪问题到JTextArea对象的setText方法。使用另一个类像JButton使用setText但JTextArea死锁。任何人都可以向我解释为什么这是发生和下面的代码有什么问题:
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");
}
});
}
}
推荐答案
您的主要方法必须包装到 invokeLater
或 invokeAndWait
规则在EventDispashThread 上创建 Swing GUI
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);
}
});
}
这篇关于在Swing中的JTextArea上使用setText时发生死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!