Java ProgressMonitor is not working

Sam YC picture Sam YC · Jul 21, 2012 · Viewed 7.4k times · Source

My code as below is not working, can anyone tell me why? Please also correct my code, I am very new to Java. Besides that, I am searching for the "loading panel component", something like ProgressMonitor but maybe more attractive and which animates better. Please suggest me if anyone has used such things before.

public class Main extends JFrame {

    private JPanel contentPane;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main frame = new Main();
                    frame.setVisible(true);

                    ProgressMonitor pm = new ProgressMonitor(frame, "Loading...", 
                            "waiting...",
                            0, 100000);

                    for (int i = 0 ; i < 100000 ; i ++){

                        pm.setProgress(i);
                        pm.setNote("Testing");
                        System.out.println(i);

                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Main() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
    }

}

Answer

Robin picture Robin · Jul 21, 2012

As @Mark Rotteveel already indicated, you are keeping the EDT (Event Dispatch Thread) occupied. The tutorial on 'How to show progress bars/monitors' contains valuable information and code samples.

But basically it comes down to moving your calculations to a worker Thread (e.g. using a SwingWorker), and showing the ProgressMonitor on the EDT. It is up to the worker thread to indicate to the ProgressMonitor what progress has already been made.

And here is a direct link to the sample code of that tutorial which clearly shows how the work is done in the SwingWorker extension (the Task class in that example), and how the ProgressMonitor gets updated by adding a PropertyChangeListener to the SwingWorker, where the listener passes the progress to the ProgressMonitor.

I would also suggest to read the Concurrency in Swing tutorial which contains more information on how to handle Threads in combination with Swing, and why you can't/shouldn't do heavy calculations on the EDT