Java/Swing JFC/ProgressBar
Содержание
- 1 A demonstration of the JProgressBar component
- 2 A demonstration of the ProgressMonitor toolbar
- 3 Create a horizontal progress bar
- 4 Create a ProgressBar
- 5 Create a vertical progress bar
- 6 Creating a JProgressBar Component with an Unknown Maximum
- 7 Creating a modal progress dialog
- 8 Displaying the Percentage Done on a JProgressBar Component
- 9 Getting and Setting the Values of a JProgressBar Component
- 10 Implement a progressbar in your application
- 11 Listening for Value Changes in a JProgressBar Component
- 12 ProgressBar Demo
- 13 ProgressBar Demo 2
- 14 ProgressBar Demo: long task
- 15 Progressbar demo: set selection background, selection foreground and foreground
- 16 Progress bar Sample
- 17 ProgressBar Step
- 18 ProgressMonitor Demo
- 19 Sample Progress
- 20 Use an actual input file to monitor rather than inducing progress manually
- 21 When information on the task"s progress is available, the progress bar can be made determinate:
A demonstration of the JProgressBar component
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
// SwingProgressBarExample.java // A demonstration of the JProgressBar component. The component tracks the // progress of a for loop. // import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; public class SwingProgressBarExample extends JPanel {
JProgressBar pbar; static final int MY_MINIMUM = 0; static final int MY_MAXIMUM = 100; public SwingProgressBarExample() { pbar = new JProgressBar(); pbar.setMinimum(MY_MINIMUM); pbar.setMaximum(MY_MAXIMUM); add(pbar); } public void updateBar(int newValue) { pbar.setValue(newValue); } public static void main(String args[]) { final SwingProgressBarExample it = new SwingProgressBarExample(); JFrame frame = new JFrame("Progress Bar Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(it); frame.pack(); frame.setVisible(true); for (int i = MY_MINIMUM; i <= MY_MAXIMUM; i++) { final int percent = i; try { SwingUtilities.invokeLater(new Runnable() { public void run() { it.updateBar(percent); } }); java.lang.Thread.sleep(100); } catch (InterruptedException e) { ; } } }
}
</source>
A demonstration of the ProgressMonitor toolbar
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
// ProgressMonitorExample.java // A demonstration of the ProgressMonitor toolbar. A timer is used to induce // progress. This example also shows how to use the UIManager properties // associated with progress monitors. // import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.ProgressMonitor; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; public class ProgressMonitorExample extends JFrame implements ActionListener {
static ProgressMonitor pbar; static int counter = 0; public ProgressMonitorExample() { super("Progress Monitor Demo"); setSize(250, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pbar = new ProgressMonitor(null, "Monitoring Progress", "Initializing . . .", 0, 100); // Fire a timer every once in a while to update the progress. Timer timer = new Timer(500, this); timer.start(); setVisible(true); } public static void main(String args[]) { UIManager.put("ProgressMonitor.progressText", "This is progress?"); UIManager.put("OptionPane.cancelButtonText", "Go Away"); new ProgressMonitorExample(); } public void actionPerformed(ActionEvent e) { // Invoked by the timer every half second. Simply place // the progress monitor update on the event queue. SwingUtilities.invokeLater(new Update()); } class Update implements Runnable { public void run() { if (pbar.isCanceled()) { pbar.close(); System.exit(1); } pbar.setProgress(counter); pbar.setNote("Operation is " + counter + "% complete"); counter += 2; } }
}
</source>
Create a horizontal progress bar
<source lang="java">
import javax.swing.JProgressBar; public class Main {
public static void main(String[] argv) throws Exception { int minimum = 0; int maximum = 100; JProgressBar progress = new JProgressBar(minimum, maximum); }
}
</source>
Create a ProgressBar
<source lang="java">
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; public class Main extends JFrame {
JProgressBar current = new JProgressBar(0, 2000); int num = 0; public Main() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pane = new JPanel(); current.setValue(0); current.setStringPainted(true); pane.add(current); setContentPane(pane); } public void iterate() { while (num < 2000) { current.setValue(num); try { Thread.sleep(1000); } catch (InterruptedException e) { } num += 95; } } public static void main(String[] arguments) { Main frame = new Main(); frame.pack(); frame.setVisible(true); frame.iterate(); }
}
</source>
Create a vertical progress bar
<source lang="java">
import javax.swing.JProgressBar; public class Main {
public static void main(String[] argv) throws Exception { int minimum = 0; int maximum = 100; JProgressBar progress = new JProgressBar(JProgressBar.VERTICAL, minimum, maximum); }
}
</source>
Creating a JProgressBar Component with an Unknown Maximum
<source lang="java">
import javax.swing.JProgressBar; public class Main {
public static void main(String[] argv) throws Exception { // Create a horizontal progress bar int min = 0; int max = 100; JProgressBar progress = new JProgressBar(min, max); // Play animation progress.setIndeterminate(true); }
}
</source>
Creating a modal progress dialog
<source lang="java">
import java.awt.BorderLayout; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JProgressBar; public class Main {
public static void main(String[] args) { JFrame parentFrame = new JFrame(); parentFrame.setSize(500, 150); JLabel jl = new JLabel(); jl.setText("Count : 0"); parentFrame.add(BorderLayout.CENTER, jl); parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); parentFrame.setVisible(true); final JDialog dlg = new JDialog(parentFrame, "Progress Dialog", true); JProgressBar dpb = new JProgressBar(0, 500); dlg.add(BorderLayout.CENTER, dpb); dlg.add(BorderLayout.NORTH, new JLabel("Progress...")); dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); dlg.setSize(300, 75); dlg.setLocationRelativeTo(parentFrame); Thread t = new Thread(new Runnable() { public void run() { dlg.setVisible(true); } }); t.start(); for (int i = 0; i <= 500; i++) { jl.setText("Count : " + i); dpb.setValue(i); if(dpb.getValue() == 500){ dlg.setVisible(false); System.exit(0); } try { Thread.sleep(25); } catch (InterruptedException e) { e.printStackTrace(); } } dlg.setVisible(true); }
}
</source>
Displaying the Percentage Done on a JProgressBar Component
<source lang="java">
import javax.swing.JProgressBar; public class Main {
public static void main(String[] argv) throws Exception { int minimum = 0; int maximum = 100; JProgressBar progress = new JProgressBar(minimum, maximum); // Overlay a string showing the percentage done progress.setStringPainted(true); }
}
</source>
Getting and Setting the Values of a JProgressBar Component
<source lang="java">
import javax.swing.JProgressBar; public class Main {
public static void main(String[] argv) throws Exception { int minimum = 0; int maximum = 100; JProgressBar progress = new JProgressBar(minimum, maximum); // Get the current value int value = progress.getValue(); // Get the minimum value int min = progress.getMinimum(); // Get the maximum value int max = progress.getMaximum(); // Change the minimum value int newMin = 0; progress.setMinimum(newMin); // Change the maximum value int newMax = 256; progress.setMaximum(newMax); // Set the value; the new value will be forced into the bar"s range int newValue = 33; progress.setValue(newValue); }
}
</source>
Implement a progressbar in your application
<source lang="java">
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; public class Main extends JPanel {
JProgressBar pbar; static int min = 0; static int max = 100; public Main() { pbar = new JProgressBar(); pbar.setMinimum(min); pbar.setMaximum(max); add(pbar); JFrame frame = new JFrame("Progress Bar Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(this); frame.pack(); frame.setVisible(true); for (int i = min; i <= max; i++) { final int percent = i; try { SwingUtilities.invokeLater(new Runnable() { public void run() { updateBar(percent); } }); Thread.sleep(100); } catch (InterruptedException e) { } } } public void updateBar(int newValue) { pbar.setValue(newValue); } public static void main(String args[]) { new Main(); }
}
</source>
Listening for Value Changes in a JProgressBar Component
<source lang="java">
import javax.swing.JProgressBar; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Main {
public static void main(String[] argv) throws Exception { int minimum = 0; int maximum = 100; JProgressBar progress = new JProgressBar(minimum, maximum); progress.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { JProgressBar comp = (JProgressBar) evt.getSource(); int value = comp.getValue(); int min = comp.getMinimum(); int max = comp.getMaximum(); } }); }
}
</source>
ProgressBar Demo
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JProgressBar; import javax.swing.border.Border; public class AProgressBar {
public static void main(String args[]) { JProgressBar aJProgressBar = new JProgressBar(); aJProgressBar.setValue(50); JProgressBar bJProgressBar = new JProgressBar(); bJProgressBar.setValue(25); bJProgressBar.setStringPainted(true); Border border = BorderFactory.createTitledBorder("Reading File"); bJProgressBar.setBorder(border); JProgressBar cJProgressBar = new JProgressBar(JProgressBar.VERTICAL); cJProgressBar.setValue(75); cJProgressBar.setBorderPainted(false); JProgressBar dJProgressBar = new JProgressBar(JProgressBar.VERTICAL); dJProgressBar.setValue(100); dJProgressBar.setString("Ack"); dJProgressBar.setStringPainted(true); JFrame theFrame = new JFrame("ProgressBars R Us"); theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = theFrame.getContentPane(); contentPane.add(aJProgressBar, BorderLayout.NORTH); contentPane.add(bJProgressBar, BorderLayout.SOUTH); contentPane.add(cJProgressBar, BorderLayout.EAST); contentPane.add(dJProgressBar, BorderLayout.WEST); theFrame.setSize(300, 200); theFrame.setVisible(true); }
}
</source>
ProgressBar Demo 2
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.awt.BorderLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.Timer; /*
* ProgressBarDemo2.java is a 1.4 application that requires these files: * LongTask.java SwingWorker.java */
public class ProgressBarDemo2 extends JPanel implements ActionListener {
public final static int ONE_SECOND = 1000; private JProgressBar progressBar; private Timer timer; private JButton startButton; private LongTask task; private JTextArea taskOutput; private String newline = "\n"; public ProgressBarDemo2() { super(new BorderLayout()); task = new LongTask(); //Create the demo"s UI. startButton = new JButton("Start"); startButton.setActionCommand("start"); startButton.addActionListener(this); progressBar = new JProgressBar(0, task.getLengthOfTask()); progressBar.setValue(0); //We call setStringPainted, even though we don"t want the //string to show up until we switch to determinate mode, //so that the progress bar height stays the same whether //or not the string is shown. progressBar.setStringPainted(true); //get space for the string progressBar.setString(""); //but don"t paint it taskOutput = new JTextArea(5, 20); taskOutput.setMargin(new Insets(5, 5, 5, 5)); taskOutput.setEditable(false); JPanel panel = new JPanel(); panel.add(startButton); panel.add(progressBar); add(panel, BorderLayout.PAGE_START); add(new JScrollPane(taskOutput), BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); //Create a timer. timer = new Timer(ONE_SECOND, new ActionListener() { public void actionPerformed(ActionEvent evt) { progressBar.setValue(task.getCurrent()); String s = task.getMessage(); if (s != null) { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); progressBar.setString(null); //display % string } taskOutput.append(s + newline); taskOutput.setCaretPosition(taskOutput.getDocument() .getLength()); } if (task.isDone()) { Toolkit.getDefaultToolkit().beep(); timer.stop(); startButton.setEnabled(true); progressBar.setValue(progressBar.getMinimum()); progressBar.setString(""); //hide % string } } }); } /** * Called when the user presses the start button. */ public void actionPerformed(ActionEvent evt) { progressBar.setIndeterminate(true); startButton.setEnabled(false); task.go(); timer.start(); } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("ProgressBarDemo2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new ProgressBarDemo2(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application"s GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
} /**
* This is the 3rd version of SwingWorker (also known as SwingWorker 3), an * abstract class that you subclass to perform GUI-related work in a dedicated * thread. For instructions on and examples of using this class, see: * * http://java.sun.ru/docs/books/tutorial/uiswing/misc/threads.html * * Note that the API changed slightly in the 3rd version: You must now invoke * start() on the SwingWorker after creating it. */
abstract class SwingWorker {
private Object value; // see getValue(), setValue() /** * Class to maintain reference to current worker thread under separate * synchronization control. */ private static class ThreadVar { private Thread thread; ThreadVar(Thread t) { thread = t; } synchronized Thread get() { return thread; } synchronized void clear() { thread = null; } } private ThreadVar threadVar; /** * Get the value produced by the worker thread, or null if it hasn"t been * constructed yet. */ protected synchronized Object getValue() { return value; } /** * Set the value produced by worker thread */ private synchronized void setValue(Object x) { value = x; } /** * Compute the value to be returned by theget
method. */ public abstract Object construct(); /** * Called on the event dispatching thread (not on the worker thread) after * theconstruct
method has returned. */ public void finished() { } /** * A new method that interrupts the worker thread. Call this method to force * the worker to stop what it"s doing. */ public void interrupt() { Thread t = threadVar.get(); if (t != null) { t.interrupt(); } threadVar.clear(); } /** * Return the value created by theconstruct
method. Returns * null if either the constructing thread or the current thread was * interrupted before a value was produced. * * @return the value created by theconstruct
method */ public Object get() { while (true) { Thread t = threadVar.get(); if (t == null) { return getValue(); } try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate return null; } } } /** * Start a thread that will call theconstruct
method and * then exit. */ public SwingWorker() { final Runnable doFinished = new Runnable() { public void run() { finished(); } }; Runnable doConstruct = new Runnable() { public void run() { try { setValue(construct()); } finally { threadVar.clear(); } SwingUtilities.invokeLater(doFinished); } }; Thread t = new Thread(doConstruct); threadVar = new ThreadVar(t); } /** * Start the worker thread. */ public void start() { Thread t = threadVar.get(); if (t != null) { t.start(); } }
} class LongTask {
private int lengthOfTask; private int current = 0; private boolean done = false; private boolean canceled = false; private String statMessage; public LongTask() { //Compute length of task... //In a real program, this would figure out //the number of bytes to read or whatever. lengthOfTask = 1000; } /** * Called from ProgressBarDemo to start the task. */ public void go() { final SwingWorker worker = new SwingWorker() { public Object construct() { current = 0; done = false; canceled = false; statMessage = null; return new ActualTask(); } }; worker.start(); } /** * Called from ProgressBarDemo to find out how much work needs to be done. */ public int getLengthOfTask() { return lengthOfTask; } /** * Called from ProgressBarDemo to find out how much has been done. */ public int getCurrent() { return current; } public void stop() { canceled = true; statMessage = null; } /** * Called from ProgressBarDemo to find out if the task has completed. */ public boolean isDone() { return done; } /** * Returns the most recent status message, or null if there is no current * status message. */ public String getMessage() { return statMessage; } /** * The actual long running task. This runs in a SwingWorker thread. */ class ActualTask { ActualTask() { //Fake a long task, //making a random amount of progress every second. while (!canceled && !done) { try { Thread.sleep(1000); //sleep for a second current += Math.random() * 100; //make some progress if (current >= lengthOfTask) { done = true; current = lengthOfTask; } statMessage = "Completed " + current + " out of " + lengthOfTask + "."; } catch (InterruptedException e) { System.out.println("ActualTask interrupted"); } } } }
}
</source>
ProgressBar Demo: long task
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.awt.*; import java.awt.event.*; import javax.swing.*; /*
* ProgressBarDemo.java is a 1.4 application that requires these files: * LongTask.java * SwingWorker.java */
public class ProgressBarDemo extends JPanel
implements ActionListener { public final static int ONE_SECOND = 1000; private JProgressBar progressBar; private Timer timer; private JButton startButton; private LongTask task; private JTextArea taskOutput; private String newline = "\n"; public ProgressBarDemo() { super(new BorderLayout()); task = new LongTask(); //Create the demo"s UI. startButton = new JButton("Start"); startButton.setActionCommand("start"); startButton.addActionListener(this); progressBar = new JProgressBar(0, task.getLengthOfTask()); progressBar.setValue(0); progressBar.setStringPainted(true); taskOutput = new JTextArea(5, 20); taskOutput.setMargin(new Insets(5,5,5,5)); taskOutput.setEditable(false); taskOutput.setCursor(null); //inherit the panel"s cursor //see bug 4851758 JPanel panel = new JPanel(); panel.add(startButton); panel.add(progressBar); add(panel, BorderLayout.PAGE_START); add(new JScrollPane(taskOutput), BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); //Create a timer. timer = new Timer(ONE_SECOND, new ActionListener() { public void actionPerformed(ActionEvent evt) { progressBar.setValue(task.getCurrent()); String s = task.getMessage(); if (s != null) { taskOutput.append(s + newline); taskOutput.setCaretPosition( taskOutput.getDocument().getLength()); } if (task.isDone()) { Toolkit.getDefaultToolkit().beep(); timer.stop(); startButton.setEnabled(true); setCursor(null); //turn off the wait cursor progressBar.setValue(progressBar.getMinimum()); } } }); } /** * Called when the user presses the start button. */ public void actionPerformed(ActionEvent evt) { startButton.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); task.go(); timer.start(); } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("ProgressBarDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new ProgressBarDemo(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application"s GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
} class LongTask {
private int lengthOfTask; private int current = 0; private boolean done = false; private boolean canceled = false; private String statMessage; public LongTask() { //Compute length of task... //In a real program, this would figure out //the number of bytes to read or whatever. lengthOfTask = 1000; } /** * Called from ProgressBarDemo to start the task. */ public void go() { final SwingWorker worker = new SwingWorker() { public Object construct() { current = 0; done = false; canceled = false; statMessage = null; return new ActualTask(); } }; worker.start(); } /** * Called from ProgressBarDemo to find out how much work needs * to be done. */ public int getLengthOfTask() { return lengthOfTask; } /** * Called from ProgressBarDemo to find out how much has been done. */ public int getCurrent() { return current; } public void stop() { canceled = true; statMessage = null; } /** * Called from ProgressBarDemo to find out if the task has completed. */ public boolean isDone() { return done; } /** * Returns the most recent status message, or null * if there is no current status message. */ public String getMessage() { return statMessage; } /** * The actual long running task. This runs in a SwingWorker thread. */ class ActualTask { ActualTask() { //Fake a long task, //making a random amount of progress every second. while (!canceled && !done) { try { Thread.sleep(1000); //sleep for a second current += Math.random() * 100; //make some progress if (current >= lengthOfTask) { done = true; current = lengthOfTask; } statMessage = "Completed " + current + " out of " + lengthOfTask + "."; } catch (InterruptedException e) { System.out.println("ActualTask interrupted"); } } } }
} /**
* This is the 3rd version of SwingWorker (also known as * SwingWorker 3), an abstract class that you subclass to * perform GUI-related work in a dedicated thread. For * instructions on and examples of using this class, see: * * http://java.sun.ru/docs/books/tutorial/uiswing/misc/threads.html * * Note that the API changed slightly in the 3rd version: * You must now invoke start() on the SwingWorker after * creating it. */
abstract class SwingWorker {
private Object value; // see getValue(), setValue() /** * Class to maintain reference to current worker thread * under separate synchronization control. */ private static class ThreadVar { private Thread thread; ThreadVar(Thread t) { thread = t; } synchronized Thread get() { return thread; } synchronized void clear() { thread = null; } } private ThreadVar threadVar; /** * Get the value produced by the worker thread, or null if it * hasn"t been constructed yet. */ protected synchronized Object getValue() { return value; } /** * Set the value produced by worker thread */ private synchronized void setValue(Object x) { value = x; } /** * Compute the value to be returned by theget
method. */ public abstract Object construct(); /** * Called on the event dispatching thread (not on the worker thread) * after theconstruct
method has returned. */ public void finished() { } /** * A new method that interrupts the worker thread. Call this method * to force the worker to stop what it"s doing. */ public void interrupt() { Thread t = threadVar.get(); if (t != null) { t.interrupt(); } threadVar.clear(); } /** * Return the value created by theconstruct
method. * Returns null if either the constructing thread or the current * thread was interrupted before a value was produced. * * @return the value created by theconstruct
method */ public Object get() { while (true) { Thread t = threadVar.get(); if (t == null) { return getValue(); } try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate return null; } } }
/**
* Start a thread that will call the construct
method
* and then exit.
*/
public SwingWorker() {
final Runnable doFinished = new Runnable() {
public void run() { finished(); }
};
Runnable doConstruct = new Runnable() {
public void run() {
try {
setValue(construct());
}
finally {
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}
/**
* Start the worker thread.
*/
public void start() {
Thread t = threadVar.get();
if (t != null) {
t.start();
}
}
}
</source>
Progressbar demo: set selection background, selection foreground and foreground
<source lang="java">
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class JProgressBarDemo extends JFrame {
protected int minValue = 0; protected int maxValue = 100; protected int counter = 0; protected JProgressBar progressBar; public JProgressBarDemo() { super("JProgressBar Demo"); setSize(300, 100); UIManager.put("ProgressBar.selectionBackground", Color.black); UIManager.put("ProgressBar.selectionForeground", Color.white); UIManager.put("ProgressBar.foreground", new Color(8, 32, 128)); progressBar = new JProgressBar(); progressBar.setMinimum(minValue); progressBar.setMaximum(maxValue); progressBar.setStringPainted(true); JButton start = new JButton("Start"); start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Thread runner = new Thread() { public void run() { counter = minValue; while (counter <= maxValue) { Runnable runme = new Runnable() { public void run() { progressBar.setValue(counter); } }; SwingUtilities.invokeLater(runme); counter++; try { Thread.sleep(100); } catch (Exception ex) { } } } }; runner.start(); } }); getContentPane().add(progressBar, BorderLayout.CENTER); getContentPane().add(start, BorderLayout.WEST); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; addWindowListener(wndCloser); setVisible(true); } public static void main(String[] args) { new JProgressBarDemo(); }
}
</source>
Progress bar Sample
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JProgressBar; import javax.swing.border.Border; public class ProgressSample {
public static void main(String args[]) { JFrame f = new JFrame("JProgressBar Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = f.getContentPane(); JProgressBar progressBar = new JProgressBar(); progressBar.setValue(25); progressBar.setStringPainted(true); Border border = BorderFactory.createTitledBorder("Reading..."); progressBar.setBorder(border); content.add(progressBar, BorderLayout.NORTH); f.setSize(300, 100); f.setVisible(true); }
}
</source>
ProgressBar Step
<source lang="java">
/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress
- /
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; public class ProgressBarStep {
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(); Runnable runner = new Runnable() { public void run() { int value = progressBar.getValue(); progressBar.setValue(value + 1); } }; for (int i = minimum; i < maximum; i++) { try { SwingUtilities.invokeAndWait(runner); // our job for each step is to just sleep Thread.sleep(DELAY); } catch (InterruptedException ignoredException) { } catch (InvocationTargetException ignoredException) { } } } } public static void main(String args[]) { // Initialize 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); String title = (args.length == 0 ? "Stepping Progress" : args[0]); JFrame theFrame = new JFrame(title); theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = theFrame.getContentPane(); contentPane.add(aJProgressBar, BorderLayout.NORTH); contentPane.add(aJButton, BorderLayout.SOUTH); theFrame.setSize(300, 200); theFrame.setVisible(true); }
}
</source>
ProgressMonitor Demo
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.awt.*; import java.awt.event.*; import javax.swing.*; /*
* ProgressMonitorDemo.java is a 1.4 application that requires these files: * LongTask.java * SwingWorker.java */
public class ProgressMonitorDemo extends JPanel
implements ActionListener { public final static int ONE_SECOND = 1000; private ProgressMonitor progressMonitor; private Timer timer; private JButton startButton; private LongTask task; private JTextArea taskOutput; private String newline = "\n"; public ProgressMonitorDemo() { super(new BorderLayout()); task = new LongTask(); //Create the demo"s UI. startButton = new JButton("Start"); startButton.setActionCommand("start"); startButton.addActionListener(this); taskOutput = new JTextArea(5, 20); taskOutput.setMargin(new Insets(5,5,5,5)); taskOutput.setEditable(false); add(startButton, BorderLayout.PAGE_START); add(new JScrollPane(taskOutput), BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); //Create a timer. timer = new Timer(ONE_SECOND, new TimerListener()); } /** * The actionPerformed method in this class * is called each time the Timer "goes off". */ class TimerListener implements ActionListener { public void actionPerformed(ActionEvent evt) { progressMonitor.setProgress(task.getCurrent()); String s = task.getMessage(); if (s != null) { progressMonitor.setNote(s); taskOutput.append(s + newline); taskOutput.setCaretPosition( taskOutput.getDocument().getLength()); } if (progressMonitor.isCanceled() || task.isDone()) { progressMonitor.close(); task.stop(); Toolkit.getDefaultToolkit().beep(); timer.stop(); if (task.isDone()) { taskOutput.append("Task completed." + newline); } else { taskOutput.append("Task canceled." + newline); } startButton.setEnabled(true); } } } /** * Called when the user presses the start button. */ public void actionPerformed(ActionEvent evt) { progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this, "Running a Long Task", "", 0, task.getLengthOfTask()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2 * ONE_SECOND); startButton.setEnabled(false); task.go(); timer.start(); } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("ProgressMonitorDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new ProgressMonitorDemo(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application"s GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
} /**
* This is the 3rd version of SwingWorker (also known as * SwingWorker 3), an abstract class that you subclass to * perform GUI-related work in a dedicated thread. For * instructions on and examples of using this class, see: * * http://java.sun.ru/docs/books/tutorial/uiswing/misc/threads.html * * Note that the API changed slightly in the 3rd version: * You must now invoke start() on the SwingWorker after * creating it. */
abstract class SwingWorker {
private Object value; // see getValue(), setValue() /** * Class to maintain reference to current worker thread * under separate synchronization control. */ private static class ThreadVar { private Thread thread; ThreadVar(Thread t) { thread = t; } synchronized Thread get() { return thread; } synchronized void clear() { thread = null; } } private ThreadVar threadVar; /** * Get the value produced by the worker thread, or null if it * hasn"t been constructed yet. */ protected synchronized Object getValue() { return value; } /** * Set the value produced by worker thread */ private synchronized void setValue(Object x) { value = x; } /** * Compute the value to be returned by theget
method. */ public abstract Object construct(); /** * Called on the event dispatching thread (not on the worker thread) * after theconstruct
method has returned. */ public void finished() { } /** * A new method that interrupts the worker thread. Call this method * to force the worker to stop what it"s doing. */ public void interrupt() { Thread t = threadVar.get(); if (t != null) { t.interrupt(); } threadVar.clear(); } /** * Return the value created by theconstruct
method. * Returns null if either the constructing thread or the current * thread was interrupted before a value was produced. * * @return the value created by theconstruct
method */ public Object get() { while (true) { Thread t = threadVar.get(); if (t == null) { return getValue(); } try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate return null; } } }
/**
* Start a thread that will call the construct
method
* and then exit.
*/
public SwingWorker() {
final Runnable doFinished = new Runnable() {
public void run() { finished(); }
};
Runnable doConstruct = new Runnable() {
public void run() {
try {
setValue(construct());
}
finally {
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}
/**
* Start the worker thread.
*/
public void start() {
Thread t = threadVar.get();
if (t != null) {
t.start();
}
}
} class LongTask {
private int lengthOfTask; private int current = 0; private boolean done = false; private boolean canceled = false; private String statMessage; public LongTask() { //Compute length of task... //In a real program, this would figure out //the number of bytes to read or whatever. lengthOfTask = 1000; } /** * Called from ProgressBarDemo to start the task. */ public void go() { final SwingWorker worker = new SwingWorker() { public Object construct() { current = 0; done = false; canceled = false; statMessage = null; return new ActualTask(); } }; worker.start(); } /** * Called from ProgressBarDemo to find out how much work needs * to be done. */ public int getLengthOfTask() { return lengthOfTask; } /** * Called from ProgressBarDemo to find out how much has been done. */ public int getCurrent() { return current; } public void stop() { canceled = true; statMessage = null; } /** * Called from ProgressBarDemo to find out if the task has completed. */ public boolean isDone() { return done; } /** * Returns the most recent status message, or null * if there is no current status message. */ public String getMessage() { return statMessage; } /** * The actual long running task. This runs in a SwingWorker thread. */ class ActualTask { ActualTask() { //Fake a long task, //making a random amount of progress every second. while (!canceled && !done) { try { Thread.sleep(1000); //sleep for a second current += Math.random() * 100; //make some progress if (current >= lengthOfTask) { done = true; current = lengthOfTask; } statMessage = "Completed " + current + " out of " + lengthOfTask + "."; } catch (InterruptedException e) { System.out.println("ActualTask interrupted"); } } } }
}
</source>
Sample Progress
<source lang="java">
/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress
- /
import java.awt.ruponent; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.ProgressMonitor; import javax.swing.Timer; public class SampleProgress {
static ProgressMonitor monitor; static int progress; static Timer timer; static class ProgressMonitorHandler implements ActionListener { // Called by Timer public void actionPerformed(ActionEvent actionEvent) { if (monitor == null) return; if (monitor.isCanceled()) { System.out.println("Monitor canceled"); timer.stop(); } else { progress += 3; monitor.setProgress(progress); monitor.setNote("Loaded " + progress + " files"); } } } public static void main(String args[]) { JFrame frame = new JFrame("ProgressMonitor Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(0, 1)); // Define Start Button JButton startButton = new JButton("Start"); ActionListener startActionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { Component parent = (Component) actionEvent.getSource(); monitor = new ProgressMonitor(parent, "Loading Progress", "Getting Started...", 0, 200); progress = 0; } }; startButton.addActionListener(startActionListener); contentPane.add(startButton); // Define Manual Increase Button // Pressing this button increases progress by 5 JButton increaseButton = new JButton("Manual Increase"); ActionListener increaseActionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { if (monitor == null) return; if (monitor.isCanceled()) { System.out.println("Monitor canceled"); } else { progress += 5; monitor.setProgress(progress); monitor.setNote("Loaded " + progress + " files"); } } }; increaseButton.addActionListener(increaseActionListener); contentPane.add(increaseButton); // Define Automatic Increase Button // Start Timer to increase progress by 3 every 250 ms JButton autoIncreaseButton = new JButton("Automatic Increase"); ActionListener autoIncreaseActionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { if (monitor != null) { if (timer == null) { timer = new Timer(250, new ProgressMonitorHandler()); } timer.start(); } } }; autoIncreaseButton.addActionListener(autoIncreaseActionListener); contentPane.add(autoIncreaseButton); frame.setSize(300, 200); frame.setVisible(true); }
}
</source>
Use an actual input file to monitor rather than inducing progress manually
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
// ProgressMonitorInputExample.java // Simpilar to the ProgressMonitorExample except that we can now use an // actual input file to monitor rather than inducing progress manually. // The file to load should be passed as a command line argument. // import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.JOptionPane; import javax.swing.ProgressMonitorInputStream; public class ProgressMonitorInputExample {
public ProgressMonitorInputExample(String filename) { ProgressMonitorInputStream monitor; try { monitor = new ProgressMonitorInputStream(null, "Loading " + filename, new FileInputStream(filename)); while (monitor.available() > 0) { byte[] data = new byte[38]; monitor.read(data); System.out.write(data); } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Unable to find file: " + filename, "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { ; } } public static void main(String args[]) { new ProgressMonitorInputExample(args[0]); }
}
</source>
When information on the task"s progress is available, the progress bar can be made determinate:
<source lang="java">
import javax.swing.JProgressBar; public class Main {
public static void main(String[] argv) throws Exception { // Create a horizontal progress bar int min = 0; int max = 100; JProgressBar progress = new JProgressBar(min, max); int value = 33; progress.setValue(value); progress.setIndeterminate(false); }
}
</source>