Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How can I force a JLabel to update after setText()?

Posted on 1999-07-13
6
Medium Priority
?
3,004 Views
Last Modified: 2013-11-23
JDK 1.1.7A and Swing, on Windows NT

In a simple Java application I have a JButton "btnGo" and a JLabel "lblStatus" within a JPanel.

When I click the Go button, I want the status label to immediately display the text "Working...", then I want to
carry out some time-intensive tasks. However, the label text won't update until the tasks have all been completed.

I can simulate this by making the thread sleep for 3 seconds (see code below). It waits three seconds and then
displays the status message.

Is there some way I can force the status label to repaint before the call to Thread.sleep?

Thanks.

class MyActionListener implements ActionListener
{
   public void actionPerformed(ActionEvent event)
   {
      Object object = event.getSource();

      if (object == btnGo)
      {
         lblStatus.setText("Working...");
            
         try {Thread.sleep(3000);}
         catch (Exception e) {}
      }
   }
}
0
Comment
Question by:wagtail
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 1

Expert Comment

by:BillyAbbott
ID: 1245917
you could try putting a lblStatus.repaint() call in after the setText line.


0
 
LVL 7

Expert Comment

by:conick
ID: 1245918
The GUI does not get updated until the event thread gets done.
(Im pretty sure repaint() or revalidate() will wait also)

Any long process that starts from the event thread should run in a new thread.  That way the GUI can repaint itself if it needs it.  Any change in the GUI from the new thread needs to be done in the event thread (or main thread) (you can use invokeLater()).

If repaint() or revalidate() doesnt work leave a comment if you want an example.
0
 

Author Comment

by:wagtail
ID: 1245919
Tried repaint() and revalidate() but no luck.

I'd appreciate that example, thanks...

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 16

Expert Comment

by:heyhey_
ID: 1245920
you definitely MUST put all the time-intensive tasks inside another Thread.

otherwise you are effectivly blocking the UI thread (even with Thread.sleep())
0
 
LVL 7

Accepted Solution

by:
conick earned 400 total points
ID: 1245921
Heres a working example:
Notice the Thread.sleep is in a different thread so the event thread can return right away (and change the GUI to "waiting")
The invokeLater method is another thread but it is executed in the event thread when the long task is completed.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ThreadTest extends JPanel  {
     JLabel label;
     JButton button;
     
     ThreadTest()  {
          setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
          setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
          JPanel panel1= new JPanel();
          panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
          label= new JLabel("Not Waiting");
          panel1.add(label);
          add(panel1);
          JPanel panel2= new JPanel();
          panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
          button= new JButton("GO");
          button.addActionListener(new TestListener());
          panel2.add(button);
          add(panel2);
     }
     
     public static void main(String args[])  {
          JFrame frame= new JFrame("Thread Test");
          frame.addWindowListener(new WindowAdapter()  {
               public void windowClosing(WindowEvent e)  {
                    System.exit(0);
               }
          });
          frame.setContentPane(new ThreadTest());
          frame.pack();
          frame.setVisible(true);
     }
     class TestListener implements ActionListener  {
          public void actionPerformed(ActionEvent e)  {
               label.setText("Waiting");    
               Thread t= new Thread()  {
                    public void run()  {
                         try {Thread.sleep(3000);}
                         catch (Exception ex) {ex.printStackTrace();}
                         SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                          label.setText("Done Waiting");
                               }
                           });
                    }
               };
               t.start();
          }
     }
}
Let me know if you have any questions on how or why it works.
0
 

Author Comment

by:wagtail
ID: 1245922
conick, thank you *very* much. This is a truly great solution. Nice one!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org Go to that link and select download selenium in the right hand column That will then direct you to their download page. From that p…
The viewer will learn how to implement Singleton Design Pattern in Java.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.
Suggested Courses

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question