Swing:无法让JButton更新 - repaint()无法正常工作 [英] Swing: Can't get JButton to update - repaint() not working

查看:194
本文介绍了Swing:无法让JButton更新 - repaint()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用Swing来创建一个简单的GUI。它包含一个 JFrame ,我在其上放置了一个 JButton ,当点击它时,会调用一些其他代码约。返回3秒钟。

I'm using Swing for the first time to create a simple GUI. It consists of a JFrame upon which I have placed a single JButton which, when clicked, calls some other code which takes approx. 3 seconds to return.

在调用此代码之前,在 actionPerformed()中,我想要更新按钮上的文本通知用户正在进行处理。我的问题是,直到3秒钟的呼叫返回后,按钮上的文字才会更新。我希望在通话过程中出现更新的文本,之后我会将其更改回来。

Just before the call to this code, in actionPerformed(), I want to update the text on the button to inform the user that processing is occuring. My problem is that the text on the button does not update until after the 3-second call has returned. I want the updated text to be present during the call, then I'll change it back afterwards.

调用 repaint() JButton 上的$ c>没有做任何事情并在 JFrame 上调用它会导致线程AWT-EventQueue-0中的异常java.lang.NullPointerException 单击按钮时抛出。

Calling repaint() on the JButton doesn't do anything and calling it on the JFrame results in "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" being thrown when I click the button.

推荐答案

发生的事情是3秒代码在GUI线程中执行,因此按钮没有机会更新,直到完成。

What's happening is that the 3-second code is executing in the GUI thread, so the button doesn't have a chance to update until it's done.

要解决此问题,请启动 SwingWorker 进行长时间运行;那么你在等待它时仍然可以自由地在GUI中做事。

To solve this, start a SwingWorker to do the long-running operation; then you'll still be free to do things in the GUI while you're waiting for it.

这是一个情侣关于这个主题的tutorial / uiswing / concurrency /rel =nofollow noreferrer>教程,上面引用的 SwingWorker Javadocs也有一些代码。

Here are a couple of tutorials on the subject, and the SwingWorker Javadocs referenced above have some code also.

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();
}

这篇关于Swing:无法让JButton更新 - repaint()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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