Swing:无法让JButton更新 - repaint()无效

Wil*_*iam 7 java swing repaint swingworker

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

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

当我点击按钮时,调用repaint()on JButton不会执行任何操作并在JFrame结果中调用它Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.

Mic*_*ers 15

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

要解决这个问题,请启动一个SwingWorker长期运行的操作; 那么在你等待的时候,你仍然可以自由地在GUI中做事.

这里有几个关于这个主题的教程,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();
}
Run Code Online (Sandbox Code Playgroud)


jjn*_*guy 10

这里的问题是你的长时间运行任务阻塞了通常会绘制GUI的线程.

通常的做法是将更长时间运行的任务抛到另一个线程中.

这可以使用a相当容易地完成SwingWorker.

这个问题也可能提供一些有用的信息.