我第一次使用 Swing 创建一个简单的 GUI。它由一个 JFrame
组成,我在其上放置了一个 JButton
,单击它时会调用一些其他代码,这大约需要3 秒返回。
就在调用此代码之前,在 actionPerformed()
中,我想更新按钮上的文本以通知用户正在进行处理。我的问题是按钮上的文本直到 3 秒调用返回后才更新。我希望在通话期间显示更新后的文本,然后我会在之后将其改回。
在 JButton
上调用 repaint()
不会执行任何操作,在 JFrame
上调用它会导致“Exception in单击按钮时抛出线程“AWT-EventQueue-0”java.lang.NullPointerException
”。
最佳答案
发生的事情是 3 秒代码在 GUI 线程中执行,因此按钮在完成之前没有机会更新。
为了解决这个问题,启动一个SwingWorker
做长时间运行的操作;那么在等待它的时候,您仍然可以在 GUI 中自由地做事。
这是一个couple的 tutorials关于这个主题,上面引用的 SwingWorker
Javadocs 也有一些代码。
示例代码
public void actionPerformed(ActionEvent e) {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
// Call complicated code here
return null;
// If you want to return something other than null, change
// the generic type to something other than Void.
// This method's return value will be available via get() once the
// operation has completed.
}
@Override
protected void done() {
// get() would be available here if you want to use it
myButton.setText("Done working");
}
};
myButton.setText("Working...");
worker.execute();
}
关于java - Swing:无法让 JButton 更新 - repaint() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/977740/