0

I want to make a ProgressBar move gradually using a Jbutton. To achieve this I am using a for loop and the method Thread.sleep. The problem is that insted of moving a tiny bit every second (the progress bar) after pressing the button, the program waits until the loop finishes and then does instantly move the progress up. When I take the loop outside of the button listener it works as I want but I really need it to work when pressing the button. Here is the code:

progressBar.setOrientation(SwingConstants.VERTICAL);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(50);
panel1.setLayout(null);
panel1.add(progressBar);
progressBar.setBounds(40,6,100,100);

button1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int counter = 5;
        for (int i = 0; i < 5; i++) {
            progressBar.setValue(progressBar.getValue() + counter);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
});

If anyone can help me I will be very grateful!

1 Answers1

2

Your code runs on the Event Dispatcher Thread (EDT). That thread is responsible for handling events, but also for repainting. Because it's just one thread, the repainting only occurs after your method ends.

There are some ways to solve this. In your case, a javax.swing.Timer would probably be easiest. Instead of running the loop in a single method, the button click starts a timer that runs every second. When it's done the timer can cancel itself. A slightly more difficult alternative is to use a SwingWorker. You could publish data in the doInBackGround method, and override process to perform the updates to the progress bar.

For more information, please read Concurrency in Swing.

Rob Spoor
  • 6,186
  • 1
  • 19
  • 20
  • I don't really know how to start the timer by clicking the button can you specify if you have the time to – Georgi Georgiev Dec 25 '22 at 17:21
  • You create a new `Timer` with its own `ActionListener`, and start that. The official tutorial can be found at https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html, and an example at https://examples.javacodegeeks.com/desktop-java/swing/timer-swing/java-swing-timer-example/ – Rob Spoor Dec 25 '22 at 19:03