JLabel does not change 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 the Green and Run function label, but when I enter the function, it does not change color to yellow (the RestartSSH function takes 5-6 seconds, but during this time the labels do not change colors and captures). Where am I mistaken in painting?

+4
source share
3 answers
  • Make your JLabel opaque so you can set its background color.
  • Run RestartSSH in a separate thread, or your GUI will not 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 SwingUtilities.invokeLater call)

+13
source

JLabels are opaque by default, so their background is not painted by default. Try:

 jLabel2.setOpaque(true); 

or you may need to rename after changing the color:

 jLabel2.repaint(); 
+5
source

I suspect your restartSSH() method is blocking the flow of sending events . One approach is to use SwingWorker , as suggested in this example . This will allow you to show the progress of the reboot process and correctly set the label when this is done.

+2
source

Source: https://habr.com/ru/post/1336945/


All Articles