Home ยป Working with JProgressBar in Java Swing tutorial

Working with JProgressBar in Java Swing tutorial

JProgressBar is a component in Java Swing used to display the progress of a task. It provides a visual indication of how much of a task has been completed and can be used for both determinate (known length) and indeterminate (unknown length) tasks.

This tutorial will cover the following topics:

1. Creating a Basic JProgressBar

The simplest way to create a progress bar is by using the default constructor or specifying the minimum and maximum values, which represent the progress range.

Example 1: Basic JProgressBar

import javax.swing.*;

public class JProgressBarExample1 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JProgressBar Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 150);

            // Create a progress bar with a range from 0 to 100
            JProgressBar progressBar = new JProgressBar(0, 100);

            // Set initial progress value
            progressBar.setValue(25);

            frame.add(progressBar);
            frame.setVisible(true);
        });
    }
}

Explanation:

We create a JProgressBar with a range from 0 to 100.
The initial value of the progress bar is set to 25, meaning the task is 25% complete.
The progress bar is added to the frame and displayed.

2. Determinate Progress Bar

In a determinate progress bar, you know how long a task will take (or have an idea of its progress). The progress bar reflects this by updating its value as the task progresses.

Example 2: Simulating Progress with Determinate JProgressBar

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JProgressBarExample2 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Determinate JProgressBar Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 150);

            JProgressBar progressBar = new JProgressBar(0, 100);
            progressBar.setValue(0);
            progressBar.setStringPainted(true); // Show percentage

            // Timer to simulate task progress
            Timer timer = new Timer(100, new ActionListener() {
                int progress = 0;

                @Override
                public void actionPerformed(ActionEvent e) {
                    progress += 5;
                    progressBar.setValue(progress);

                    if (progress >= 100) {
                        ((Timer) e.getSource()).stop(); // Stop timer when task is complete
                    }
                }
            });
            timer.start();

            frame.add(progressBar);
            frame.setVisible(true);
        });
    }
}

Explanation:

The JProgressBar is created with a range from 0 to 100.
A Timer simulates the progress of a task by incrementing the progress value by 5 every 100 milliseconds.
The setStringPainted(true) method enables the display of a percentage inside the progress bar.

3. Indeterminate Progress Bar

An indeterminate progress bar is used when the length of the task is unknown. The progress bar shows a continuous animation (without any numerical progress) to indicate that the task is ongoing.

Example 3: Indeterminate JProgressBar

import javax.swing.*;

public class JProgressBarExample3 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Indeterminate JProgressBar Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 150);

            // Create an indeterminate progress bar
            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true); // Enable indeterminate mode
            progressBar.setString("Loading..."); // Show text on the progress bar

            frame.add(progressBar);
            frame.setVisible(true);
        });
    }
}

Explanation:

We create a JProgressBar and set it to indeterminate mode using setIndeterminate(true).
The progress bar displays a continuous animation with the message “Loading…” to indicate that a task is in progress.

4. Updating JProgressBar Dynamically in the Background

In a real-world scenario, you will often need to update a progress bar while performing a background task. Swing provides a class called SwingWorker to handle background operations without freezing the user interface.

Example 4: Using SwingWorker to Update JProgressBar

import javax.swing.*;
import java.util.concurrent.TimeUnit;

public class JProgressBarExample4 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingWorker JProgressBar Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 150);

            JProgressBar progressBar = new JProgressBar(0, 100);
            progressBar.setValue(0);
            progressBar.setStringPainted(true);

            // SwingWorker to perform a background task
            SwingWorker<Void, Void> worker = new SwingWorker<>() {
                @Override
                protected Void doInBackground() throws Exception {
                    for (int i = 0; i <= 100; i += 5) {
                        progressBar.setValue(i); // Update progress bar
                        TimeUnit.MILLISECONDS.sleep(200); // Simulate a time-consuming task
                    }
                    return null;
                }

                @Override
                protected void done() {
                    JOptionPane.showMessageDialog(frame, "Task Completed!");
                }
            };

            worker.execute(); // Start the background task

            frame.add(progressBar);
            frame.setVisible(true);
        });
    }
}

Explanation:

SwingWorker is used to perform a background task, and we update the JProgressBar during the execution of the task.
The doInBackground() method simulates a task by incrementing the progress and sleeping for 200 milliseconds between increments.
Once the task is completed, a message box is displayed using JOptionPane.

5. Customizing JProgressBar Appearance

You can customize the appearance of the JProgressBar by changing its orientation, background color, foreground color, and border.

Example 5: Customizing the Appearance of JProgressBar

import javax.swing.*;
import java.awt.*;

public class JProgressBarExample5 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Customized JProgressBar");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 150);

            JProgressBar progressBar = new JProgressBar(0, 100);
            progressBar.setValue(50);
            progressBar.setStringPainted(true); // Show percentage
            progressBar.setForeground(Color.GREEN); // Set progress color
            progressBar.setBackground(Color.LIGHT_GRAY); // Set background color
            progressBar.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); // Add a black border

            frame.add(progressBar);
            frame.setVisible(true);
        });
    }
}

Explanation:

The progress bar's foreground color is set to green using setForeground(), and its background is set to light gray with setBackground().
We add a border around the progress bar using setBorder().
The percentage of the progress bar is displayed using setStringPainted(true).

6. Vertical JProgressBar

By default, JProgressBar is horizontal, but you can set it to vertical orientation using setOrientation(JProgressBar.VERTICAL).

Example 6: Vertical JProgressBar

import javax.swing.*;

public class JProgressBarExample6 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Vertical JProgressBar Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(150, 400);

            // Create a vertical progress bar
            JProgressBar progressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 100);
            progressBar.setValue(75); // Set progress value
            progressBar.setStringPainted(true); // Show percentage

            frame.add(progressBar);
            frame.setVisible(true);
        });
    }
}

Explanation:

The orientation of the JProgressBar is set to vertical using setOrientation(JProgressBar.VERTICAL).
The value of the progress is set to 75%, and the percentage is displayed inside the progress bar.

Conclusion

JProgressBar is a useful component in Java Swing for providing feedback on the progress of a task.

You can create both determinate and indeterminate progress bars, customize their appearance, and update them dynamically while performing background tasks.

With SwingWorker, you can easily manage background tasks while ensuring that your user interface remains responsive.

Summary of Key Points:

Basic Progress Bar: Create a JProgressBar and set its range and value.
Determinate Progress Bar: Use when you know the task's length, and update the progress bar accordingly.
Indeterminate Progress Bar: Use for tasks of unknown length, showing continuous activity.
SwingWorker: Update the progress bar while performing background tasks.
Custom Appearance: Customize colors, borders, and orientation of the progress bar.
Vertical Progress Bar: Set the progress bar to vertical orientation for alternative designs.

You may also like