0

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)

  • you start the timer 200 times... why? ... maybe you can post your complete code and what you are trying to do exactly ... read this https://stackoverflow.com/help/minimal-reproducible-example – JavaMan Nov 12 '20 at 16:11
  • 2
    The point of using a Timer is to replace looping logic in your application The Timer becomes the loop because it generates an event every second (in your example). Your listener then responds to the event. See: https://stackoverflow.com/questions/30417719/update-a-label-with-a-swing-timer/30417857#30417857 for the most basic example. Also, don't use a null layout and setBounds(...). Swing was designed to be used with layout managers. – camickr Nov 12 '20 at 16:27

1 Answers1

0

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.

WJS
  • 36,363
  • 4
  • 24
  • 39