Reputation: 437
I wrote a little code to change the colours of a few buttons to stimulate a random sequence offlashing colours. i have set a timer to do this for me but i just dont know how to stop it
Heres my code
Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int buttons[] = new int[9];
for (int j = 0; j < buttons.length; j++) {
// System.out.println("times");
Component button = frame.getContentPane().getComponent(j);
int Red = new Random().nextInt(255 - 1) + 1;
int Green = new Random().nextInt(255 - 1) + 1;
int Blue = new Random().nextInt(255 - 1) + 1;
button.setBackground(new Color(Red, Green, Blue));
SwingUtilities.updateComponentTreeUI(button);
}
}// }
}); timer.start();
Upvotes: 2
Views: 645
Reputation: 1842
There's a few ways you can do it, here's a couple of quick approaches.
One method is by utilising System.currentTimeMillis()
:
private Timer timer;
private final int DELAY = 100;
private final int DURATION = 10_000;
private long startTime;
public void timerExample() {
timer = new Timer(DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (System.currentTimeMillis() >= startTime + DURATION) {
System.out.println("Done");
timer.stop();
} else {
System.out.println("Tick");
}
}
});
startTime = System.currentTimeMillis();
timer.start();
}
This one will stop the Timer
if the current time is greater than the startTime
+ DURATION
.
Another method is this use of a counter:
private Timer timer;
private final int DELAY = 100;
private final int DURATION = 10_000;
private final int TOTAL_TICKS = DURATION / DELAY;
private int tickCounter = 0;
public void timerExample() {
timer = new Timer(DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (++tickCounter == TOTAL_TICKS) {
System.out.println("Done");
timer.stop();
} else {
System.out.println("Tick");
}
}
});
timer.start();
}
With DELAY
as 100ms and DURATION
as 10,000ms you can calculate the total number of Timer ticks required e.g. 10,000 / 100 = 100 ticks.
Each time action listener is fired, it checks if the total number of ticks are reached, and if so stops the timer.
Upvotes: 2