GUI在运行ActionEvent之前无法直观更新 [英] GUI not updating visually before running ActionEvent

查看:168
本文介绍了GUI在运行ActionEvent之前无法直观更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了进一步说明,我有一个看起来像这样的GUI:

To expound a little more, I have a GUI that looks like:

然后我在OK按钮上有一个动作监听器,起始如下:

Then I have an action listener on the OK button that starts like:

//OK Button Action Listener
private void okButtonActionPerformed(ActionEvent e) {   
    //Enable/Disable Buttons
    okButton.setEnabled(false);
    cancelButton.setEnabled(true);
    updateCheckbox.setEnabled(false);
    //Move on to a series of other methods here...

哪个应该,从理论上讲,要做到这一点:

Which should, in theory, make this happen:

但是,我会得到以下内容,直到所有方法和连接到OK按钮的其他内容都完成:

However, instead, I get the following until ALL methods and other things connected to the OK button are completed:

这个显然不可能发生,因为这个想法是让取消按钮可用,OK按钮和其他几个勾选框在程序的持续时间内不可用(图2),相反,它在半状态下冻结(图3)。有没有办法解决这个问题?

This obviously can't happen, because the idea is to make the cancel button available and the OK button and several other tick-boxes unavailable for the duration of the program (Image 2), where, instead, it freezes in a half-state (Image 3). Is there any way to combat this?

推荐答案

每次从GUI执行逻辑时,你应该使用以下的SwingWorker方式:

Every time you execute logic from the GUI you should be using the SwingWorker in the following way:

SwingWorker myWorker= new SwingWorker<String, Void>() {
    @Override
    protected String doInBackground() throws Exception {
        //Execute your logic
        return null;
    }
};
myWorker.execute();

如果要从此逻辑内部更新GUI,请使用InvokeLater:

If you want to update the GUI from inside this logic use InvokeLater:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        //To update your GUI
    }
});

通过这种方式,您可以确保您的逻辑和GUI保持响应。

With this you can be sure that both your logic and your GUI stay responsive.

修改:

您还可以使用 invokeAndWait 如果这更符合您的需求。 链接到相关答案

You could also use invokeAndWait if this suits your needs more. Link to related answer

这篇关于GUI在运行ActionEvent之前无法直观更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆