【发布时间】:2015-07-22 18:56:44
【问题描述】:
考虑一下这个由两个按钮组成的基本 Swing 程序:
public class main {
public static void main(String[] args) {
JFrame jf = new JFrame("hi!");
JPanel mainPanel = new JPanel(new GridLayout());
JButton longAction = new JButton("long action");
longAction.addActionListener(event -> doLongAction());
JButton testSystemOut = new JButton("test System.out");
testSystemOut.addActionListener(event -> System.out.println("this is a test"));
mainPanel.add(longAction);
mainPanel.add(testSystemOut);
jf.add(mainPanel);
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public static void doLongAction() {
SwingUtilities.invokeLater(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("Interrupted!");
}
System.out.println("Finished long action");
});
}
}
我希望我的第二个按钮 testSystemOut 在第一个按钮进行长时间操作时可用(在这里,我在其中设置了 3 秒的睡眠时间)。我可以通过手动将doLongAction() 放入Thread 并调用start() 来做到这一点。但我读过我应该改用SwingUtilities,它的工作原理与这里的EventQueue 完全一样。但是,如果我这样做,我的 Button 会在其操作期间冻结。
为什么?
【问题讨论】:
标签: java multithreading swing