Java Tutorial/Swing/JProgressBar — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 15:31, 31 мая 2010
Содержание
- 1 A progress bar is used for lengthy tasks.
- 2 Creating a JProgressBar Component with an Unknown Maximum
- 3 Creating a modal progress dialog
- 4 Customizing JProgressBar Look and Feel
- 5 Displaying the Percentage Done on a JProgressBar Component
- 6 Getting and Setting the Values of a JProgressBar Component
- 7 Handling JProgressBar Events: notification of data model changes through a ChangeListener
- 8 JProgressBar
- 9 Labeling a JProgressBar
- 10 Listening for Value Changes in a JProgressBar Component
- 11 ProgressBar and Task
- 12 Set all the values at once by using the model
- 13 SwingWorker and ProgressBar
- 14 Using an Indeterminate JProgressBar
- 15 Virtical JProgressBar
A progress bar is used for lengthy tasks.
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.JProgressBar;
import javax.swing.Timer;
public class ProgressBar {
public static void main(String[] args) {
final Timer timer;
final JProgressBar progressBar = new JProgressBar();
final JButton button = new JButton("Start");
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
f.add(progressBar);
f.add(button);
ActionListener updateProBar = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int val = progressBar.getValue();
if (val >= 100) {
// timer.stop();
button.setText("End");
return;
}
progressBar.setValue(++val);
}
};
timer = new Timer(50, updateProBar);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
button.setText("Start");
} else if (button.getText() != "End") {
timer.start();
button.setText("Stop");
}
}
});
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Creating a JProgressBar Component with an Unknown Maximum
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);
}
}
Creating a modal progress dialog
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);
}
}
Customizing JProgressBar Look and Feel
Property StringObject TypeProgressBar.backgroundColorProgressBar.borderBorderProgressBar.cellLengthIntegerProgressBar.cellSpacingIntegerProgressBar.cycleTimeIntegerProgressBar.fontFontProgressBar.foregroundColorProgressBar.highlightColorProgressBar.horizontalSizeDimensionProgressBar.repaintIntervalIntegerProgressBar.selectionBackgroundColorProgressBar.selectionForegroundColorProgressBar.shadowColorProgressBar.verticalSizeDimensionProgressBarUIString
Displaying the Percentage Done on a JProgressBar Component
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);
}
}
Getting and Setting the Values of a JProgressBar Component
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);
}
}
Handling JProgressBar Events: notification of data model changes through a ChangeListener
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class BoundedChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent changeEvent) {
Object source = changeEvent.getSource();
if (source instanceof JProgressBar) {
JProgressBar theJProgressBar = (JProgressBar) source;
System.out.println("ProgressBar changed: " + theJProgressBar.getValue());
} else {
System.out.println("Something changed: " + source);
}
}
}
public class ProgressBarStepBoundedChangeListener {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame("Stepping Progress");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar aJProgressBar = new JProgressBar(JProgressBar.VERTICAL);
aJProgressBar.setStringPainted(true);
aJProgressBar.addChangeListener(new BoundedChangeListener());
for (int i = 0; i < 10; i++) {
aJProgressBar.setValue(i++);
Thread.sleep(100);
}
frame.add(aJProgressBar, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
JProgressBar
There are five different constructors for JProgressBar:
public JProgressBar()
JProgressBar aJProgressBar = new JProgressBar();
public JProgressBar(int orientation)
JProgressBar aJProgressBar = new JProgressBar(JProgressBar.VERTICAL);
JProgressBar bJProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);
public JProgressBar(int minimum, int maximum)
JProgressBar aJProgressBar = new JProgressBar(0, 500);
public JProgressBar(int orientation, int minimum, int maximum)
JProgressBar aJProgressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 1000);
public JProgressBar(BoundedRangeModel model)
// Data model, initial value 0, range 0-250, and extent of 0
DefaultBoundedRangeModel model = new DefaultBoundedRangeModel(0, 0, 0, 250);
JProgressBar aJProgressBar = new JProgressBar(model);
Labeling a JProgressBar
To display the percentage completed [100 X (value-minimum)/(maximum-minimum)], call the public void setStringPainted(boolean newValue) method with a parameter of true.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
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();
for (int i = minimum; i < maximum; i++) {
try {
int value = progressBar.getValue();
progressBar.setValue(value + 1);
Thread.sleep(DELAY);
} catch (InterruptedException ignoredException) {
}
}
}
}
public static void main(String args[]) {
JFrame frame = new JFrame("Stepping Progress");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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);
frame.add(aJProgressBar, BorderLayout.NORTH);
frame.add(aJButton, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Listening for Value Changes in a JProgressBar Component
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();
}
});
}
}
ProgressBar and Task
/*
* Copyright (c) 1995 - 2008 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:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions 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 nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
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.SwingWorker;
public class ProgressBarDemo2 extends JPanel implements ActionListener,
PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
private Task task;
class Task extends SwingWorker<Void, Void> {
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
// Initialize progress property.
setProgress(0);
// Sleep for at least one second to simulate "startup".
try {
Thread.sleep(1000 + random.nextInt(2000));
} catch (InterruptedException ignore) {
}
while (progress < 100) {
// Sleep for up to one second.
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {
}
// Make random progress.
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
/*
* Executed in event dispatch thread
*/
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
taskOutput.append("Done!\n");
}
}
public ProgressBarDemo2() {
super(new BorderLayout());
// Create the demo"s UI.
startButton = new JButton("Start");
startButton.setActionCommand("start");
startButton.addActionListener(this);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
// Call setStringPainted now so that the progress bar height
// stays the same whether or not the string is shown.
progressBar.setStringPainted(true);
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));
}
/**
* Invoked when the user presses the start button.
*/
public void actionPerformed(ActionEvent evt) {
progressBar.setIndeterminate(true);
startButton.setEnabled(false);
// Instances of javax.swing.SwingWorker are not reusuable, so
// we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
/**
* Invoked when task"s progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressBar.setIndeterminate(false);
progressBar.setValue(progress);
taskOutput.append(String.format("Completed %d%% of task.\n", progress));
}
}
/**
* Create the GUI and show it. As with all GUI code, this must run on the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
// 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();
}
});
}
}
Set all the values at once by using the model
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);
int newValue = 10;
int newMin = 0;
int newMax = 100;
progress.getModel().setRangeProperties(newValue, 0, newMin, newMax, false);
}
}
SwingWorker and ProgressBar
/*
* Copyright (c) 1995 - 2008 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:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions 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 nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
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.SwingWorker;
public class ProgressBarDemo extends JPanel implements ActionListener,
PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
private Task task;
class Task extends SwingWorker<Void, Void> {
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
// Initialize progress property.
setProgress(0);
while (progress < 100) {
// Sleep for up to one second.
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {
}
// Make random progress.
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
setCursor(null); // turn off the wait cursor
taskOutput.append("Done!\n");
}
}
public ProgressBarDemo() {
super(new BorderLayout());
// Create the demo"s UI.
startButton = new JButton("Start");
startButton.setActionCommand("start");
startButton.addActionListener(this);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
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));
}
/**
* Invoked when the user presses the start button.
*/
public void actionPerformed(ActionEvent evt) {
startButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Instances of javax.swing.SwingWorker are not reusuable, so
// we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
/**
* Invoked when task"s progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
taskOutput.append(String.format("Completed %d%% of task.\n", task
.getProgress()));
}
}
/**
* Create the GUI and show it. As with all GUI code, this must run on the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
// 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();
}
});
}
}
Using an Indeterminate JProgressBar
Indeterminate mode: Progress bar bounces back and forth from side to side
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
public class ProgressBarStepIndeterminate {
public static void main(String args[]) {
JFrame frame = new JFrame("Stepping Progress");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar aJProgressBar = new JProgressBar(JProgressBar.VERTICAL);
aJProgressBar.setStringPainted(true);
aJProgressBar.setIndeterminate(true);
frame.add(aJProgressBar, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Virtical JProgressBar
To change the label to a fixed string, call the public void setString(String newValue) method and setStringPainted(true). On a vertical progress bar, the string is drawn rotated, so a longer string will fit better.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
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();
for (int i = minimum; i < maximum; i++) {
try {
int value = progressBar.getValue();
progressBar.setValue(value + 1);
Thread.sleep(DELAY);
} catch (InterruptedException ignoredException) {
}
}
}
}
public class ProgressBarStep {
public static void main(String args[]) {
JFrame frame = new JFrame("Stepping Progress");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar aJProgressBar = new JProgressBar(JProgressBar.VERTICAL);
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);
frame.add(aJProgressBar, BorderLayout.NORTH);
frame.add(aJButton, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}