我想在事件发生时将按钮背景颜色更改 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();
}