Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JLabel setText not working in actionListener

 
Harshal Mahajan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Harshal Mahajan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For more information
http://java.sun.com/products/jfc/tsc/articles/painting/
 
Rob Camick
Ranch Hand
Posts: 2612
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic