简体   繁体   English

JLabel不会改变颜色

[英]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 ). 在我输入功能标签之前是绿色和运行,但是当我进入功能时它不会将颜色变为黄色(功能RestartSSH正在执行5-6秒,但在此期间标签不会改变颜色和捕获)。 Where I make mistake in painting ? 我在绘画中犯了错误?

  • Make your JLabel opaque so you can set its background colour. 使您的JLabel不透明,以便您可以设置其背景颜色。
  • Perform RestartSSH in a separate thread, or your GUI won't respond to events. 在单独的线程中执行RestartSSH ,否则您的GUI将不响应事件。

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 ) (更新:添加了对SwingUtilities.invokeLater调用)

JLabels is opaque by default, so their's background isn't painted by default. JLabels默认是不透明的,因此默认情况下不会绘制它们的背景。 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 . 我怀疑你的restartSSH()方法阻塞了事件派发线程 One approach is to use a SwingWorker , as suggested in this example . 一种方法是使用SwingWorker ,如本例所示 This would allow you to show the progress of the restart process and set the label appropriately when done. 这将允许您显示重新启动过程的进度并在完成后适当地设置标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM