闪烁的JTextField的颜色 [英] Flashing color of a JTextField

查看:183
本文介绍了闪烁的JTextField的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JTextField,如果它有无效的内容被清除。我想背景闪烁红色一两次,以向用户表明这已经发生。我试过:

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

但是这是一个红色的短暂时间,它不可能被看到。任何提示?

解决方案

正确的解决方案,几乎到达eric,是使用一个Swing计时器,在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 > = totalCount){
((Timer)evt.getSource())。stop();
}
}
count ++;
}
});
timer.start();
}

通过 flashMyField(someTextField,注意:代码既没有编译也没有测试。


($ .RED,500,2000);



<

I have a JTextField that is cleared if it has invalid content. I would like the background to flash red one or two times to indicate to the user that this has happened. I have tried:

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

But it is red for such a brief time that it cannot possibly be seen. Any tips?

解决方案

The correct solution, almost arrive at by just eric, is to use a Swing Timer, since all the code in the Timer's ActionListener will be called on the Swing event thread, and this can prevent intermittent and frustrating errors from occurring. For example:

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();
}

And it would be called via flashMyField(someTextField, Color.RED, 500, 2000);

Caveat: code has been neither compiled nor tested.

这篇关于闪烁的JTextField的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆