Display percentage information on JProgressBar in Java

Description

The following code shows how to display percentage information on JProgressBar.

To display the percentage completed [100 X (value-minimum)/(maximum-minimum)], call the public void setStringPainted(boolean newValue) method with a parameter of true.

Example


// w ww .  ja  v a  2  s .  c o m
  
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class Main {
  static class BarThread extends Thread {
    private static int DELAY = 500;

    JProgressBar progressBar;

    public BarThread(JProgressBar bar) {
      progressBar = bar;
    }

    public void run() {
      int minimum = progressBar.getMinimum();
      int maximum = progressBar.getMaximum();
      for (int i = minimum; i < maximum; i++) {
        try {
          int value = progressBar.getValue();
          progressBar.setValue(value + 1);

          Thread.sleep(DELAY);
        } catch (InterruptedException ignoredException) {
        }
      }
    }
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame("Stepping Progress");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JProgressBar aJProgressBar = new JProgressBar(0, 50);
    aJProgressBar.setStringPainted(true);

    final JButton aJButton = new JButton("Start");

    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        aJButton.setEnabled(false);
        Thread stepper = new BarThread(aJProgressBar);
        stepper.start();
      }
    };
    aJButton.addActionListener(actionListener);
    frame.add(aJProgressBar, BorderLayout.NORTH);
    frame.add(aJButton, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Display percentage information on JProgressBar in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer