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 pain开发者_如何学编程ting ?
- 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
)
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();
I suspect that your restartSSH()
method is blocking the event dispatch thread. One approach is to use a SwingWorker
, as suggested in this example. This would allow you to show the progress of the restart process and set the label appropriately when done.
精彩评论