简体   繁体   中英

Change a JLabel Text while an JButton listener is working

I have a JButton, lets call it "button" and added an ActionListener to it:

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). How do I do that? Do I have to use some multi-thread-thingy? Here is the basic principle(the JLabel is called output):

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. How can I make it instantly display "test1"?

Don't use Thread.sleep(). This will prevent the GUI from repainting itself.

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.

In this case you can use a SwingWorker .

Read the section from the Swing tutorial on Concurrency for more information and an example of using a SwingWorker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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