Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JLabel doesn't change back color

Part of my function looks like this

jLabel2.setBackground(Color.YELLOW);
jLabel2.setText("Status : Idle");

boolean ok=cpu21.RestartSSH();

if(ok){
    jLabel2.setBackground(Color.GREEN);
    jLabel2.setText("Status : Run");    
}

Before I enter in function label is Green and Run, but when I come in function it doesn't chabge color to Yellow ( function RestartSSH is executing 5-6 sec, but during that time labels doesn't change colors and captures ). Where I make mistake in painting ?

like image 404
Damir Avatar asked Jan 25 '11 10:01

Damir


2 Answers

  • Make your JLabel opaque so you can set its background colour.
  • Perform RestartSSH in a separate thread, or your GUI won't respond to events.

Example:

final JLabel jLabel2 = new JLabel("HELLO");
jLabel2.setOpaque(true);
jLabel2.setBackground(Color.YELLOW);
jLabel2.setText("Status : Idle");

//perform SSH in a separate thread
Thread sshThread = new Thread(){
    public void run(){
        boolean ok=cpu21.RestartSSH();
        if(ok){
           //update the GUI in the event dispatch thread
           SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                   jLabel2.setBackground(Color.GREEN);
                   jLabel2.setText("Status : Run");
               }
           });
        }
    }
};
sshThread.start();

(Update: added call to SwingUtilities.invokeLater)

like image 174
dogbane Avatar answered Oct 03 '22 11:10

dogbane


JLabels is opaque by default, so their's background isn't painted by default. Try with:

jLabel2.setOpaque(true);

or maybe you have to call repaint after changing the color:

jLabel2.repaint();
like image 42
Jonas Avatar answered Oct 03 '22 10:10

Jonas