aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes JLabel setText not working in actionListener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JLabel setText not working in actionListener" Watch "JLabel setText not working in actionListener" New topic
Author

JLabel setText not working in actionListener

Harshal Mahajan
Greenhorn

Joined: Sep 16, 2009
Posts: 3
Hi,

I have a simple JFrame program, I have a JButton and JLabel, JLabel is initialize with some value. on button click I want to execute one process which will take more than 3 seconds, before process starts and ends i want to show process status in JLabel. but it always sets last value assigned to label when process gets executed.

public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
if(actionCommand.equals("Click Me"))
{
jlbl.setText("Process start");
someMethod();
jlbl.setText("Process end");
}
}
private void someMethod()
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}



Thanks,


harshal


Thanks,

Harshal
Harshal Mahajan
Greenhorn

Joined: Sep 16, 2009
Posts: 3
I did some research and was able to solve my problem. Hopefully it'll help those who might run into the same problem. Apparently, Swing component repainting is managed by a RepaintManager class which intercepts all paint requests and calls invokeLater() to process the pending requests on the same dispatch thread. Therefore you have no control over exactly when the repainting occurs. However, the method paintImmediately() can be used to cause a Swing component to get updated immediately.

So in my code, I added the following line immediately after the setText():

jlbl.paintImmediately(jlbl.getVisibleRect());
Harshal Mahajan
Greenhorn

Joined: Sep 16, 2009
Posts: 3
For more information
http://java.sun.com/products/jfc/tsc/articles/painting/
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2203
    
    7
Although using paintImmediately will work, that is NOT the proper solution.

Your code is executing in the Event Dispatch Thread and the sleep is blocking the EDT preventing it from repainting the label.

The proper solution is to use a separate Thread for the long running task so you don't block the EDT.

Read the section from the Swing tutorial on Concurrency for more details.

Also, use the "Code" tags when posting code so the code is formatted and readable.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: JLabel setText not working in actionListener