KulaDamian
KulaDamian

Reputation: 154

Value of JLabel is not being updated using setText() in Java

I know many people have asked this question before but I couldn't find any answer that solved my problem. My code is like this:

public void mouseClicked(MouseEvent arg0) {
    TEXT.setText("ON");
    myfunction(); //runs for a very long time
}

The original text of JLabel is "OFF". Now I want to change the text to "ON" when the mouse is clicked but the text doesn't set until myfunction() is complete (which may take several minutes).

I have tried the invalidate function, making a separate function for setting the text but nothing is working.

Please help me with this problem!

Upvotes: 1

Views: 64

Answers (1)

Neuron
Neuron

Reputation: 5833

The problem is that mouseClicked(...) is executed on the UI Thread. That is the Thread that is responsible for handling all sorts of user actions (like a mouse click) and also the drawing of components (like updating the text of the label on screen). If you execute your long running method call on the UI thread, it will be blocked and can't draw anything until execution is complete. You'll have to use multi threading to get around this problem.

The following might not be the most elegant solution, but if you are new to multi threading it will get the job done:

public void mouseClicked(MouseEvent arg0) {
    TEXT.setText("ON");
    (new Thread() {
        public void run() {
            myfunction();
        }
    }).start();
}

It will spawn a new Thread that handles your method, which will let the UI Thread continue doing its thing. consider deactivating the button that has just been clicked, so the user can't start the execution while it is already in progress (which usually is what you want..)

Upvotes: 3

Related Questions