在 JButton 侦听器工作时更改 JLabel 文本

Change a JLabel Text while an JButton listener is working

我有一个 JButton,我们将其命名为 "button" 并向其添加一个 ActionListener:

button.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent evt) { 
        call();
    }
});

它已正确添加到我的框架等。在那个 JFrame 中,我还有一个 JLabel,我想在 JButton 方法工作时更改它的文本(因为它需要大约 30 秒才能完成)。我怎么做?我必须使用一些多线程吗? 这是基本原理(JLabel 称为输出):

public void call(){
    output.setText("test1");
    try { Thread.sleep(1000);
    } catch (InterruptedException e) {}
    output.setText("test2");
}

这将导致 "output" 标签在一秒钟后更改为 "test2"。我怎样才能让它立即显示"test1"?

不要使用 Thread.sleep()。这将防止 GUI 重新绘制自身。

Do I have to use some multi-thread-thingy?

是的。

对于较长的 运行 任务,您需要启动一个单独的 Thread,这样 GUI 才能保持响应。

在这种情况下,您可以使用 SwingWorker

阅读有关 Concurrency 的 Swing 教程部分,了解更多信息和使用 SwingWorker 的示例。