Flashing color of a JTextField

…衆ロ難τιáo~ 提交于 2019-12-25 00:34:49

问题


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?


回答1:


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.




回答2:


You need to extend public class Timer Do it like so:

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

You can set Timer to execute in whatever intervals you prefer to create the flashing effect

From documentation:

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

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.



来源:https://stackoverflow.com/questions/11129951/flashing-color-of-a-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!