Java Swing Tutorials - Herong's Tutorial Examples - Version 4.11, by Dr. Herong Yang
SwingWorker Example using JProgressBar
This section provides a tutorial example on how to use java.swing.SwingWorker class the JProgressBar component on the UI. All main features of the SwingWorker class are demonstrated.
Example 4: Put everything together - This example shows you how to all features of the SwingWorker class together to create more real Swing GUI application to generate random numbers as a background task.
Here is the source code of the example program, SwingWorkerUsingProgress.java:
/* SwingWorkerUsingProgressBar.java * Copyright (c) 2014, HerongYang.com, All Rights Reserved. */ import java.beans.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class SwingWorkerUsingProgressBar { static JButton myButton; static JProgressBar myProgressBar; static JLabel myUpdate; static JTextArea myTextArea; public static void main(String[] a) { JFrame myFrame = new JFrame("Random Number Generator"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container myPane = myFrame.getContentPane(); myPane.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); setMyConstraints(c,0,0,GridBagConstraints.CENTER); myPane.add(getFieldPanel(),c); setMyConstraints(c,0,1,GridBagConstraints.CENTER); myPane.add(getButtonPanel(),c); JMenuBar myMenuBar = new JMenuBar(); myMenuBar.add(getFileMenu()); myMenuBar.add(getColorMenu()); JMenuItem myItem = new JMenuItem("Help"); myMenuBar.add(myItem); myFrame.setJMenuBar(myMenuBar); myFrame.pack(); myFrame.setVisible(true); } private static JMenu getFileMenu() { JMenu myMenu = new JMenu("File"); JMenuItem myItem = new JMenuItem("Open"); myMenu.add(myItem); myItem = new JMenuItem("Close"); myItem.setEnabled(false); myMenu.add(myItem); myMenu.addSeparator(); myItem = new JMenuItem("Exit"); myMenu.add(myItem); return myMenu; } private static JMenu getColorMenu() { JMenu myMenu = new JMenu("Color"); JMenuItem myItem = new JMenuItem("Red"); myMenu.add(myItem); myItem = new JMenuItem("Green"); myMenu.add(myItem); myItem = new JMenuItem("Blue"); myMenu.add(myItem); return myMenu; } private static JPanel getFieldPanel() { JPanel p = new JPanel(new GridBagLayout()); p.setBorder(BorderFactory.createTitledBorder("")); GridBagConstraints c = new GridBagConstraints(); setMyConstraints(c,0,0,GridBagConstraints.EAST); p.add(new JLabel("Progress:"),c); setMyConstraints(c,1,0,GridBagConstraints.WEST); myProgressBar = new JProgressBar(0, 100); p.add(myProgressBar,c); setMyConstraints(c,0,1,GridBagConstraints.EAST); p.add(new JLabel("Last number:"),c); setMyConstraints(c,1,1,GridBagConstraints.WEST); myUpdate = new JLabel(""); p.add(myUpdate,c); setMyConstraints(c,0,2,GridBagConstraints.EAST); p.add(new JLabel("All numbers:"),c); setMyConstraints(c,1,2,GridBagConstraints.WEST); myTextArea = new JTextArea(10,40); myTextArea.setLineWrap(true); myTextArea.setFont(new Font("Courier",Font.PLAIN, 12)); p.add(myTextArea,c); return p; } private static JPanel getButtonPanel() { JPanel p = new JPanel(new GridBagLayout()); myButton = new JButton("Run"); myButton.addActionListener(new MyButtonListener()); p.add(myButton); return p; } private static void setMyConstraints(GridBagConstraints c, int gridx, int gridy, int anchor) { c.gridx = gridx; c.gridy = gridy; c.anchor = anchor; } // My ActionListener class to kickoff the task static class MyButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { myButton.setText("Wait"); myButton.setEnabled(false); myTextArea.setText(""); MySwingWorker worker = new MySwingWorker(); worker.addPropertyChangeListener(new MyProgressListener()); worker.execute(); } } // My SwingWorker class to perform the task static class MySwingWorker extends SwingWorker<Integer[], Integer> { int total = 100; int wait = 100; protected Integer[] doInBackground() { Integer[] l = new Integer[total]; Random r = new Random(); try { for (int i=0; i<total; i++) { Thread.sleep(wait); Integer n = new Integer(100+r.nextInt(899)); l[i] = n; publish(n); setProgress((100*(i+1))/total); } } catch (Exception e) { e.printStackTrace(); } return l; } protected void process(java.util.List<Integer> v) { myUpdate.setText(""+(Integer)v.get(v.size()-1)); } protected void done() { try { Integer[] r = get(); String s = ""; for (int i=0; i<r.length; i++) { s += " "+r[i]; } myTextArea.setText(s); myButton.setText("Run"); myButton.setEnabled(true); } catch (Exception e) { e.printStackTrace(); } } } // My PropertyChangeListener class catch progress property changes static class MyProgressListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { if ("progress".equals(e.getPropertyName())) { myProgressBar.setValue((Integer)e.getNewValue()); } } } }
If you compile and run this example with JDK 1.8, you will see a Swing window showing up.
If you click the "Run" button to kickoff the background task, you will see the progress bar
getting updated as more random numbers are generated. See the picture below:
Note that while the random number generation is going on in the background, you can still click on menu items to perform other functions. This demonstrates us the key advantage of using the SwingWorker class, i.e. to launch a time consuming task in the background and keep the UI to be responsive.
Sample programs listed in this section have been tested with JDK 1.6.0 to 1.8.0.
Last update: 2014.
Table of Contents
Introduction of Java Swing Package
Graphics Environment of the Local System
JRadioButton - Swing Radio Button Class
JTextField - Swing Text Field Class
Menu Bar, Menus, Menu Items and Listeners
Creating Internal Frames inside the Main Frame
Layout of Components in a Container
JEditorPane - The Editor Pane Class
►SwingWorker - The Background Task Worker
SwingWorker Example using done() Method
SwingWorker Example using publish() Method
SwingWorker Example using "progress" Property