Swing,如何正确更新UI [英] Swing, how to properly update the UI
问题描述
在Swing上执行某些操作后更新UI的正确方法是什么?
What is the right way to update the UI after doing some operations on Swing?
例如,在单击按钮后,调用的方法几乎可以瞬间或需要几秒钟。实际上,所有应用程序逻辑都是通过Web服务远程完成的,因此等待应用程序响应是正常的。
For example, after clicking a button, a method is called that may be almost instant or take some seconds. In fact, all the applicaton logic is done remotely through a web service, so it's normal to wait a little bit for the application to respond.
我的按钮事件处理程序可能看起来像这样:
My eventhandler for a button may look like these:
myButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
//callWebService();
//do stuff
//updateUI(); // <----- repaint? revalidate? what?
}
});
我当前的实现调用updateUI方法,该方法在内部调用validate()和repaint()到父组件拥有UI。这有效,但有时我可以看到屏幕闪烁。我做错了吗?有没有更好的方法呢?
My current implementation calls the updateUI method which internally call validate() and repaint() to the parent component that holds the UI. This works, but sometimes I can see the screen flickering. Am I doing it wrong? Is there a better way to do it?
推荐答案
正确的方法是使用SwingWorker,但如果你想这样做手动你必须实现以下模式:
The right way would be to use SwingWorker, but if you want to do it manually you'll have to implement the following pattern:
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
new Thread() {
@Override public void run () {
//callWebService();
//do stuff
SwingUtilities.invokeLater(new Runnable(){
@Override public void run() {
//updateUI(); // <----- repaint? revalidate? what?
}
});
}
}.start();
}
对于重绘/重新验证问题,通常会调用 revalidate ()
然后 repaint()
。当然,这仅适用于您手动绘制的组件。对于您重复使用的组件,只需调用它们的值更改方法。
For the repaint/revalidate question, normally call revalidate()
then repaint()
. this is, of course, only valid for component that you manually draw. For components that you reuse, just call their value change methods.
这篇关于Swing,如何正确更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!