Getting my jProgressBar to run on a timer from 1 to 100

Jack picture Jack · Aug 12, 2012 · Viewed 8.9k times · Source

I was looking through this thread

How to make Timer countdown along with progress bar?

I would like to add this to my code so i can just get a jProgressBar and a Button, (Using netbeans preferably)

So that when I hit the button it runs from 0 to 100 steadily, I really have tried to go at this on my own and have got really mad, any help would be nice.

Answer

trashgod picture trashgod · Aug 12, 2012

Leveraging @Andrew's example,

image

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

class CountUpProgressBar extends JPanel {

    private JProgressBar bar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
    private JLabel label = new JLabel("", JLabel.CENTER);
    private Timer timer = new Timer(100, new ActionListener() {

        private int counter = 1;

        @Override
        public void actionPerformed(ActionEvent ae) {
            label.setText(String.valueOf(counter));
            bar.setValue(++counter);
            if (counter > 100) {
                timer.stop();
            }
        }
    });

    CountUpProgressBar() {
        super.setLayout(new GridLayout(0, 1));
        bar.setValue(0);
        timer.start();
        this.add(bar);
        this.add(label);
        JOptionPane.showMessageDialog(null, this);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                CountUpProgressBar cdpb = new CountUpProgressBar();
            }
        });
    }
}