Apologies If I sound stupid. I'm just starting. I've had little to no classes yet.
I wanted to apply a time delay to my for
loop. I tried with thread.sleep
but it makes the whole GUI non operational. I've been told to use Swing timer to said code, so I tried.
I have seen some tutorials I can't seem to get it working. This is part of my code:
for (int d = 0; d < 201; d++) {
//Need to insert time delay here
System.out.println(jorgegress);
progressbard.setValue(jorgegress);
}
And this is one of my attempts to get it working:
JButton buttond = new JButton("Click me");
buttond.setBounds(10, 190, 416, 63);
Timer timer;
timer = new Timer(1000, null);
timer.setRepeats(true);
buttond.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("ok this works");
for (int d = 0; d < 201; d++) {
//Need to insert time delay here
timer.start();
System.out.println(d);
progressbard.setValue(d);
}
timer.stop();
What am I doing wrong? (probably doing a lot wrong)
Try this in place of your for loop. Your button press will start the timer. The timer will stop on its own when it reaches the desired count. This is very basic. It could be further customized to take in count thresholds, delays, and even other methods to run (via lambdas).
Timer t = new Timer(0, new ActionListener() {
int count = 0;
public void actionPerformed(ActionEvent ae) {
if (count > 201) {
((Timer)ae.getSource()).stop();
}
System.out.println(jorgegress);
progressboard.setValue(jorgegress);
count++;
}
});
t.setDelay(100); // delay is in millseconds.
t.start();
You may want to lockout the button while the timer is running and then re-enable it when the timer stops. This will prevent having multiple timers going simultaneously.