gpt4 book ai didi

java - JLabel 不会改变背景颜色

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:32 28 4
gpt4 key购买 nike

我的部分功能看起来像这样

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

boolean ok=cpu21.RestartSSH();

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

在我输入功能标签之前,标签是绿色和运行,但是当我进入功能时,它不会将颜色更改为黄色(功能 RestartSSH 执行 5-6 秒,但在此期间标签不会改变颜色和捕获).我画错了哪里?

最佳答案

  • 使您的 JLabel 不透明,以便您可以设置它的背景颜色。
  • 在单独的线程中执行RestartSSH,否则您的 GUI 将不会响应事件。

例子:

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();

(更新:添加了对 SwingUtilities.invokeLater 的调用)

关于java - JLabel 不会改变背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4792644/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com