Java中的多线程操作优先级。(在GUI更新之前,对象实例化并运行?)
我希望GUI将按钮的标题从“Go”更改为“Working…”在对象实例化并实际执行工作之前。完成后,我希望按钮的标题切换回“Go”
代码如下:
private class convert implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
button.setText("Working...");
button.setEnabled(false);
anObject name = new AnObject();
boolean result = name.methodName(chooser.getSelectedFile(),encoding);
// A bunch of stuff was here but irrelevant to the question,
// so it was removed to save room.
button.setEnabled(true);
button.setText("Go");
}
实践中实际发生的是name被实例化,methodName被调用,然后按钮在屏幕上得到更新,尽管我已经告诉虚拟机先更改按钮标题
我的工作原理是,考虑到我没有使这个程序线程化,这与操作优先级、JVM的内部线程化或其他有关
有什么建议吗
# 1 楼答案
试试SwingUtilities.invokeLater()
# 2 楼答案
事件线程中会发生一个“ActionPerformed”回调,在返回之前,GUI上通常不会更新任何内容。如果你想更新gui,做点什么,然后再次更新,你需要更新gui,生成一个线程并返回。然后线程必须执行它的操作,然后执行SwingUtilities。调用调用器来更新gui
# 3 楼答案
我知道您已经接受了一个解决方案,但由于您遇到了“冻结gui”综合症,您肯定有线程问题,invokeLater无法解决您的问题。正如extraneon在上面提到的,你需要一个SwingWorker或者一些后台线程来解决这个问题。此外,我认为这是一个使用AbstractAction而不是ActionListener的好例子。例如: