简体   繁体   English

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

[英]Change a JLabel Text while an JButton listener is working

I have a JButton, lets call it "button" and added an ActionListener to it: 我有一个JButton,让我们称之为“按钮”,并向其中添加了一个ActionListener:

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

It is correctly added to my frame etc. In that JFrame I also have a JLabel, and I want to change its text while the JButton method is working(because it takes ~30 secs to finish). 它已正确添加到我的框架等中。在该JFrame中,我也有一个JLabel,并且我想在JButton方法运行时更改其文本(因为大约需要30秒才能完成)。 How do I do that? 我怎么做? Do I have to use some multi-thread-thingy? 我是否必须使用一些多线程工具? Here is the basic principle(the JLabel is called output): 这是基本原理(JLabel称为输出):

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

This will result in the "output" Label being changed to "test2" after one second. 一秒钟后,这将导致“输出”标签更改为“ test2”。 How can I make it instantly display "test1"? 如何使其立即显示“ test1”?

Don't use Thread.sleep(). 不要使用Thread.sleep()。 This will prevent the GUI from repainting itself. 这将防止GUI重新绘制自身。

Do I have to use some multi-thread-thingy? 我是否必须使用一些多线程工具?

Yes. 是。

For a long running task you need to start a separate Thread , so the GUI can remain responsive. 对于长期运行的任务,您需要启动一个单独的Thread ,以便GUI可以保持响应状态。

In this case you can use a SwingWorker . 在这种情况下,您可以使用SwingWorker

Read the section from the Swing tutorial on Concurrency for more information and an example of using a SwingWorker . 阅读Swing 并发教程中的这一节,以获取更多信息和使用SwingWorker的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM