rho*_*ron 0 java swing colors jtextfield
我有一个JTextField,如果它有无效的内容,它将被清除.我希望背景闪红色一两次,以向用户表明这种情况已经发生.我试过了:
field.setBackground(Color.RED);
field.setBackground(Color.WHITE);
Run Code Online (Sandbox Code Playgroud)
但是在这么短暂的时间内它是红色的,不可能被看到.有小费吗?
正确的解决方案,几乎是由eric来实现的,就是使用Swing Timer,因为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();
}
Run Code Online (Sandbox Code Playgroud)
它将被称为通过 flashMyField(someTextField, Color.RED, 500, 2000);
警告:代码既未编译也未经过测试.