我试图让 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/