Search code examples
javaeclipsewindowprogress-barwindowbuilder

How can I make a JProgressBar fill up during a certain interval?


Your solution works with the timer JProgressBar fill up during a certain interval however when btn is pressed the timer doesnt start any suggestions I have included the full code ?

Here is the full code:

//Packages
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


//Class
public class PickUp 
{

    private JFrame frmPickUp;

    /**
     * Launch the application.
     */
    public static void NewScreen2() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    PickUp window = new PickUp();
                    window.frmPickUp.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    @SuppressWarnings("serial")
    public class ProgressBar extends JFrame
    {
        private int c = 0;
        private Timer t;
        private JButton btn;
        private JProgressBar pBar;
        private long currentTime;

        // 15 minutes in milliseconds
        private final int waitingTime = 15 * 60 * 1000;//900000 milliseconds

        private final int delay = waitingTime / 100;//9000 == 9 seconds

        public ProgressBar()
        {

            // delay in milliseconds
            //inside the internal anonymous class, we write the code we want the timer to execute each delay
            t = new Timer(delay, new ActionListener() {

                public void actionPerformed(ActionEvent e)
                {
                    if(c <= 100) pBar.setValue(++c);
                }
            });

            btn = new JButton("Start Timer");

            // Adding an action listener: when you click the button, the timer starts
            btn.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e)
                {
                    // starting the timer, which causes it to sending ActionEvents to its Listeners
                    t.start();
                }
            });
            getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));

            getContentPane().add(btn);//Adding the button to the content pane
            //
            //Creating a progress bar from 0 to 100
            pBar = new JProgressBar(0, 100);

            // Setting the initial value of the progress bar
            pBar.setValue(c);// c == 0

            // Showing a string progress bar
            pBar.setStringPainted(true);

            //adding a changeListener to the progress bar
            pBar.addChangeListener(new ChangeListener() {

                public void stateChanged(ChangeEvent e)
                {
                    if(pBar.getValue() == 100)
                    {
                        t.stop();
                        JOptionPane.showMessageDialog(null, "Your order is ready!");

                        c = 0;
                        pBar.setValue(c);//set the initial value of the progress bar to 0 again
                    }
                }
            });

            getContentPane().add(pBar);//Adding the progress bar to the content pane

            //normal housekeeping's stuff
            pack();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            setLocationRelativeTo(null);
        }

        public void main(String[] args)
        {
            ProgressBar pb = new ProgressBar();
        }

    }

    /**
     * Create the application.
     */
    public PickUp() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */

    //Variables
    private void initialize() {
        frmPickUp = new JFrame();
        frmPickUp.setTitle("Pick Up");
        frmPickUp.getContentPane().setBackground(new Color(255, 250, 205));
        frmPickUp.getContentPane().setLayout(null);
        //Text, headings
        JLabel lblYourPizzaWill = new JLabel("Your pizza will be ready to pick up in:");
        lblYourPizzaWill.setFont(new Font("Tahoma", Font.BOLD, 12));
        lblYourPizzaWill.setBounds(109, 29, 238, 20);
        frmPickUp.getContentPane().add(lblYourPizzaWill);

        JLabel lblMins = new JLabel("15 MINS");
        lblMins.setFont(new Font("Tahoma", Font.BOLD, 16));
        lblMins.setForeground(new Color(255, 0, 0));
        lblMins.setBounds(189, 60, 82, 31);
        frmPickUp.getContentPane().add(lblMins);

        JProgressBar pBar = new JProgressBar(0, 100);
        pBar.setValue(0);
        pBar.setStringPainted(true);
        pBar.setBounds(212, 102, 146, 17);
        frmPickUp.getContentPane().add(pBar);

        JButton btn = new JButton("Start Timer");
        btn.setFont(new Font("Tahoma", Font.BOLD, 12));
        btn.setBounds(96, 98, 106, 23);
        frmPickUp.getContentPane().add(btn);
        frmPickUp.setBounds(100, 100, 450, 170);
        frmPickUp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
    }

Solution

  • You can use the Timer class to create an object, which can perform certain actions every a certain period of time (delay):

    import java.awt.EventQueue;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JProgressBar;
    import javax.swing.Timer;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    @SuppressWarnings("serial")
    public class ProgressBar extends JFrame
    {
        private int c = 0;
        private Timer t;
        private JButton btn;
        private JProgressBar pBar;
    
        // 15 minutes in milliseconds
        private final int waitingTime = 15 * 60 * 1000;// 900000 milliseconds
    
        private final int delay = waitingTime / 100;// 9000 == 9 seconds
    
        public ProgressBar()
        {
            setLayout(new FlowLayout());
    
            // delay in milliseconds
            // inside the internal anonymous class we write the code we want the timer to execute each delay
            // Instead of 50 milliseconds, you just have to write delay
            t = new Timer(delay, new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    if(c <= 100) pBar.setValue(++c);
                }
            });
    
            btn = new JButton("WAIT");
    
            // Adding an action listener: when you click the button, the timer starts
            btn.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    // starting the timer, which causes it to sending ActionEvents to its Listeners
                    t.start();
                }
            });
    
            add(btn);
    
            pBar = new JProgressBar(0, 100);
    
            // Setting the initial value of the progress bar
            pBar.setValue(c);// c == 0
    
            // Showing a string progress bar
            pBar.setStringPainted(true);
    
            // adding a changeListener to the progress bar
            pBar.addChangeListener(new ChangeListener() {
    
                @Override
                public void stateChanged(ChangeEvent e)
                {
                    if(pBar.getValue() == 100)
                    {
                        t.stop();
                        JOptionPane.showMessageDialog(null, "Your order is ready!");
    
                        c = 0;
                        pBar.setValue(c);// set the initial value of the progress bar to 0 again
                    }
                }
            });
    
            add(pBar);
    
            pack();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            setLocationRelativeTo(null);
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable() {
                public void run()
                {
                    try
                    {
                        new ProgressBar();
                    }
                    catch(Exception ex)
                    {
                        JOptionPane.showMessageDialog(null, "Fatal Error.");
                    }
                }
            });
        }
    
    }