2016-12-28 46 views
0

我想闪烁的JButton的背景颜色,但只有'睡眠'它的工作。如何闪烁任何JComponent的背景颜色?

我的代码:

@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: 我刚找出它不设置在运行时任何颜色(具有或不具有任何延迟/睡眠)。

+0

你是什么意思“只有'sleep'工作”? – ItamarG3

+0

延时工作,但颜色不变。 – tomyforever

+0

a)200毫秒很短,请尝试更长的睡眠时间。 b)你在循环该代码吗? – ItamarG3

回答

2

你需要使用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(); 

注意:不是所有组件/ JComponents真正改变通过调用后台的setBackground

+0

如何从我的类中检索ActionListener对象?因为你正在创建一个新的。如果我做新的时间(200,this),它会在actionPerformed()的第一行给我一个NullPointer。 – tomyforever

+0

我不明白你的问题。你在哪里试图检索ActionListener?什么是新时间(200,这个)?如果你在actionPerformed的第一行得到一个NullPointerException,这意味着你实际上没有把颜色放到'colors'数组中 – ControlAltDel

+0

我认为我必须使用实现我的类的ActionListener。在阅读整个文档之后https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html我发现它是我的类的actionPerformed中的一个新的ActionListener。然后我尝试了你的代码,颜色正在改变,但循环不停止。 – tomyforever

0

问题是,当您睡觉UI线程(通过TimeUnit...sleep(x))时,它将无法重新呈现更改。我敢打赌,最后的颜色确实呈现。

你需要找到触发颜色变化的另一种方法,看看定时器,特别是摆动定时器。

+0

(1-)Swing组件应在事件分派线程(EDT)上更新。所以你应该使用Swing Timer,而不是该链接中提到的其他计时器。 – camickr

+0

@camickr是的那些其他定时器不适合,谢谢 – weston