set text in label during an action event

64,295

Solution 1

The reason because it is not working right now is that the Java thread that handle the GUI refreshing also handles the events of the Listeners. So when you call the setText() method it tells the GUI thread (called EDT for Event Dispatch Thread) to update the Component, but it can't be done right now because the EDT is currently in the actionPerformed() method executing your code.

So I think you should put the code that do whatever work and change the text of your JLabel in a new thread. So the EDT starts it in the actionPerformed() and is then free to update the GUI when the text of your JLabel changes.

Something like this: (You have to implement the run method)

public void actionPerformed(ActionEvent e) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            myLabel.setText("Processing");
            //Do the job
            myLabel.setText("Processed");
        }     
    });
    t.start();
}

Ideally the setText() method and others that alter the component have to be called from the EDT itself to avoid bugs... This is not the case in the example I gave you. If you want to do it use this method:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        myLabel.setText("my text");
    }
});

Solution 2

There must be a delay between the setting of "Processing" and "Processed" JLabel text otherwise the change in text will be too quick to observe.

One way to do this is to use a Swing Timer between the 2 setText calls. Your JButton ActionListener could look like this:

public void actionPerformed(ActionEvent e) {
    label.setText("Processing...");

    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            label.setText("Processed");
        }
    };
    Timer timer = new Timer(1000, taskPerformer); // delay one sec
    timer.setRepeats(false);
    timer.start();
}
Share:
64,295
Admin
Author by

Admin

Updated on November 18, 2020

Comments

  • Admin
    Admin over 3 years

    Possible Duplicate:
    several times change label text by clicking button in swing not work

    I am using Java Swing to develop a GUI in which I use two components JButton and JLabel. The text of JLabel is initially set to "Click the button". After clicking the button I want the text of JLabel to change to "Processing".And finally to "Processed"

    So, when I click the button the control goes to ActionPerformed wherein I have set the text of JLabel to "Processing" using setText() method. The last statement in ActionPerformed is setting the text of JLabel to "Processed" using setText().

    When I run the program the label shows "Click the button".In the end it changes to "Processed". However, it never displays "Processing".