2013-05-09 42 views
1

我正在尝试更改按钮背景颜色为10次时事件发生?当事件发生时重绘功能不起作用


private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
    try { 
     for (int i = 0; i < 10; ++i) { 
      Random r = new Random(); 
      jButton2.setBackground(new Color(r.nextInt(150), r.nextInt(150), r.nextInt(150))); 
      jButton2.repaint(); 
      Thread.sleep(200); 
     } 
    } catch (Exception e) { 
     System.out.println(e.toString()); 
    } 

} 

按钮显示最后的颜色?


由于它的正常工作

int x = 0; 
Timer timer; 
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {           

    timer = new Timer(1000, new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      Random r = new Random(); 
      jButton2.setBackground(new Color(r.nextInt(150), r.nextInt(150), r.nextInt(150))); 
      jButton2.repaint(); 
      if(x==10){ 
       timer.stop(); 
       x=0; 
      } else{ 
       x++; 
      } 
     } 
    }); 
    timer.start(); 
} 
+0

很高兴你有它的工作。考虑在你的课程开始时只创建一次Random对象。没有必要重新创建它。 – 2013-05-10 02:13:39

回答

3

不要Swing事件线程调用了Thread.sleep(...),因为这使整个Swing GUI的睡觉。换句话说,你的GUI不执行绘制操作,接受没有用户输入或交互在所有并变为完全无用,而事件(也被称为ëd ispatch Ť hread或EDT)。改用Swing Timer。请查看Swing Timer Tutorial获取更多帮助。

另外看看this question的一些答案,包括mKo​​rbel的答案。

相关问题