cma.2602
cma.2602

Reputation: 23

Repaint a swing component while a thread is running

I have a thread that I start when I press the start button. What I want to do is repaint the labels so they contain the information that my thread makes changes to. The only problem I am facing is that the jLabels repaint only after the thread is done running. Can someone give me any sugestions on how I can make it repaint while the thread is runnong? Thanks.

Here is a snippet of my code:

Store m = new Store(); //Store extends Thread
private void startActionPerformed(java.awt.event.ActionEvent evt) {    
    ....
    //I get the simulation time of the store from a textbox
    //the thread runs for this number of seconds
    //when it is done, the store is closed(the open variable is set to false)
    ....

    m.start();

    while (m.isOpen()) {
        queue0.setText(String.valueOf(m.clientiCasai(0)));
        //here I will have more queues
        ....
        noOfClients.repaint(); //this is the label that should show the number of clients in queue 0
    }
}  

Upvotes: 1

Views: 395

Answers (2)

Alexander
Alexander

Reputation: 1421

Your startActionPerformed() method should not run on EventDispatchThread (EDT) which is the Thread that shall be used for all Swing Modification operations. If you block the EDT your UI will not repaint, it will freeze.

Your noOfClients.repaint() call should be done on EDT, but also your call setting the new value to queue0 label should be on EDT.

For simplification. If you your queue0.setText() call on EDT, the repainting will be done for you, so you can remove it.

This can be achieved by calling:

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            queue0.setText("<text>");
        }
    });

To solve your problem you could either pass a reference to the instance holding the method startActionPerformed() to your Store and call it from there when needed or you could start another Thread that monitors the Store progress and propagates it to the Swing EDT.

Upvotes: 1

Haroldo_OK
Haroldo_OK

Reputation: 7230

The problem is that the actual painting is also done during the EDT's event loop; your while() loop is basically preventing the EDT from proceeding. One possible workaround would be to have an extra thread that would take care of updating the label.

Upvotes: 1

Related Questions