java - 如何使任何 JComponent 的背景颜色闪烁?

标签 java swing colors background jcomponent

我试图让 JButton 的背景颜色闪烁,但只有“ sleep ”它正在工作。

我的代码:

@Override
public void actionPerformed(ActionEvent e){

  if(!empty){
  }else{
  myButton.setBackground(Color.RED);
  try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e2){}
  myButton.setBackground(Color.LIGHT_GRAY);
  try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {}
  myButton.setBackground(Color.RED);
  try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {}
  myButton.setBackground(Color.LIGHT_GRAY);
  }
  }
}

编辑: 无法发布完整代码,这么多行。 该按钮位于 GridBagLayout 内:

myButton= new Jbutton("Button!");
myButton.setBackground(Color.White);
myButton.setHorizontalAlignment(JTextField.CENTER);;
myButton.setForeground(Color.black);
GridBagConstraints gbc_myButton = new GridBagConstraints();
gbc_myButton.fill = GridBagConstraints.BOTH;
gbc_myButton.gridx = 0;
gbc_myButton.gridy = 1;
gbc_myButton.gridwidth=3;
panel.add(myButton, gbc_myButton);

编辑2: 我只是发现它在运行时没有设置任何颜色(有或没有任何延迟/ sleep )。

最佳答案

你需要使用javax.swing.Timer来做这样的动画。

final Button b = ...;
final Color[] colors = ...;
colors[0] = Color.RED;
colors[1] = Color.LIGHT_GREY;
ActionListener al = new ActionListener() {
  int loop = 0;
  public void actionPerformed(ActionEvent ae) {
    loop = (loop + 1) % colors.length;
    b.setBackground(colors[loop]);
  }
}

new Timer(200, al).start();

注意:并非所有组件/JComponent 实际上都通过调用 setBackground 来更改背景

关于java - 如何使任何 JComponent 的背景颜色闪烁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41366387/

相关文章:

java - 使用 Java Rest API 获取 Azure 订阅中的资源详细信息

java - 应用程序不会从 PHP Web 服务检索 JSON 数据。网络服务工作正常

java - JPanel按钮等

java - 单选按钮消失

java - 如何释放 Swingworker 分配的内存?

html - 用于更改 h1 中最后一个单词颜色的 CSS

java - 奇怪的异常 : Cannot cast String to Boolean when using getBoolean

java - 将一个字符串散列为几个(100-200)个无符号整数

python - Plotly:用单一颜色的填充和线条绘制面积图

linux - 将 h264 转换为原始 RGB 时 gstreamer 颜色错误