2012-06-21 109 views
0

我有一个JTextField,如果内容无效,它将被清除。我希望背景闪烁一次或两次以向用户表明发生了这种情况。我曾尝试:JTextField的闪烁颜色

field.setBackground(Color.RED); 
field.setBackground(Color.WHITE); 

但它是红色的这样一个短暂的时间,它不可能被看到。有小费吗?

回答

2

你需要扩大公共类Timer 做它像这样:

private class FlashTask extends TimerTask{ 
    public void run(){ 
     // set colors here 
    } 
} 

您可以设置Timer在执行任何间隔你希望创建闪烁的效果

从技术文档:

public void scheduleAtFixedRate(TimerTask task, long delay, long period)

安排指定在指定的延迟后开始重复固定速率执行。

+0

这是一个体面的解决方案,但我只希望它闪烁一次。问题更多的是背景没有设置为红色足够长的时间。 – rhombidodecahedron

+0

通过闪光一次你的意思是改变颜色一秒钟,然后改变回来并留在那里?或只是改变颜色并保持这种颜色,直到满足条件? “ –

+1

”没有设置为红色足够长的时间“你的意思是你需要帮助编辑更改的时间间隔? –

6

正确的解决方案几乎是由eric来完成的,因为Timer的ActionListener中的所有代码都将在Swing事件线程中调用,这可以防止发生间歇性和令人沮丧的错误。例如:

public void flashMyField(final JTextField field, Color flashColor, 
    final int timerDelay, int totalTime) { 
    final int totalCount = totalTime/timerDelay; 
    javax.swing.Timer timer = new javax.swing.Timer(timerDelay, new ActionListener(){ 
    int count = 0; 

    public void actionPerformed(ActionEvent evt) { 
     if (count % 2 == 0) { 
     field.setBackground(flashColor); 
     } else { 
     field.setBackground(null); 
     if (count >= totalCount) { 
      ((Timer)evt.getSource()).stop(); 
     } 
     } 
     count++; 
    } 
    }); 
    timer.start(); 
} 

而且,它还将通过flashMyField(someTextField, Color.RED, 500, 2000);

买者被称为:代码已经没有编制,也没有进行测试。

+0

+1 for'javax.swing.Timer' – trashgod

+0

和FYI:你应该使用Timer的原因以及为什么你看不到红色的原因与我在[这个答案]中描述的差不多。 http://stackoverflow.com/questions/11088910/timing-with-swing-animation/11090056#11090056)。 – Robin

+2

+1不错,在这个答案中,不要调用'setBackground(Color.WHITE)',它不是某些L&F的默认背景。 – Robin