FileDocCategorySizeDatePackage
JProgressBar.javaAPI DocJava SE 5 API35022Fri Aug 26 14:57:56 BST 2005javax.swing

JProgressBar

public class JProgressBar extends JComponent implements SwingConstants, Accessible
A component that, by default, displays an integer value within a bounded interval. A progress bar typically communicates the progress of some work by displaying its percentage of completion and possibly a textual display of this percentage.

To indicate that a task of unknown length is executing, you can put a progress bar into indeterminate mode. While the bar is in indeterminate mode, it animates constantly to show that work is occurring. As soon as you can determine the task's length and amount of progress, you should update the progress bar's value and switch it back to determinate mode.

Here is an example of creating a progress bar, where task is an object that returns information about the progress of some work:

progressBar = new JProgressBar(0, task.getLengthOfTask());
progressBar.setValue(0);
progressBar.setStringPainted(true);
Here is an example of updating the value of the progress bar:
progressBar.setValue(task.getCurrent());
Here is an example of putting a progress bar into indeterminate mode, and then switching back to determinate mode once the length of the task is known:
progressBar = new JProgressBar();
...//when the task of (initially) unknown length begins:
progressBar.setIndeterminate(true);
...//do some work; get length of task...
progressBar.setMaximum(newLength);
progressBar.setValue(newValue);
progressBar.setIndeterminate(false);

For complete examples and further documentation see How to Monitor Progress, a section in The Java Tutorial.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see {@link java.beans.XMLEncoder}.

see
javax.swing.plaf.basic.BasicProgressBarUI
beaninfo
attribute: isContainer false description: A component that displays an integer value.
version
1.93 12/19/03
author
Michael C. Albers
author
Kathy Walrath

Fields Summary
private static final String
uiClassID
protected int
orientation
Whether the progress bar is horizontal or vertical. The default is HORIZONTAL.
protected boolean
paintBorder
Whether to display a border around the progress bar. The default is true.
protected BoundedRangeModel
model
The object that holds the data for the progress bar.
protected String
progressString
An optional string that can be displayed on the progress bar. The default is null. Setting this to a non-null value does not imply that the string will be displayed.
protected boolean
paintString
Whether to textually display a string on the progress bar. The default is false. Setting this to true causes a textual display of the progress to be rendered on the progress bar. If the progressString is null, the percentage of completion is displayed on the progress bar. Otherwise, the progressString is rendered on the progress bar.
private static final int
defaultMinimum
The default minimum for a progress bar is 0.
private static final int
defaultMaximum
The default maximum for a progress bar is 100.
private static final int
defaultOrientation
The default orientation for a progress bar is HORIZONTAL.
protected transient ChangeEvent
changeEvent
Only one ChangeEvent is needed per instance since the event's only interesting property is the immutable source, which is the progress bar.
protected ChangeListener
changeListener
Listens for change events sent by the progress bar's model, redispatching them to change-event listeners registered upon this progress bar.
private transient Format
format
Format used when displaying percent complete.
private boolean
indeterminate
Whether the progress bar is indeterminate (true) or normal (false); the default is false.
Constructors Summary
public JProgressBar()
Creates a horizontal progress bar that displays a border but no progress string. The initial and minimum values are 0, and the maximum is 100.

see
#setOrientation
see
#setBorderPainted
see
#setStringPainted
see
#setString
see
#setIndeterminate



                                           
     
    
	this(defaultOrientation);
    
public JProgressBar(int orient)
Creates a progress bar with the specified orientation, which can be either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL. By default, a border is painted but a progress string is not. The initial and minimum values are 0, and the maximum is 100.

param
orient the desired orientation of the progress bar
see
#setOrientation
see
#setBorderPainted
see
#setStringPainted
see
#setString
see
#setIndeterminate

	this(orient, defaultMinimum, defaultMaximum);
    
public JProgressBar(int min, int max)
Creates a horizontal progress bar with the specified minimum and maximum. Sets the initial value of the progress bar to the specified minimum. By default, a border is painted but a progress string is not. The BoundedRangeModel that holds the progress bar's data handles any issues that may arise from improperly setting the minimum, initial, and maximum values on the progress bar.

param
min the minimum value of the progress bar
param
max the maximum value of the progress bar
see
BoundedRangeModel
see
#setOrientation
see
#setBorderPainted
see
#setStringPainted
see
#setString
see
#setIndeterminate

	this(defaultOrientation, min, max);
    
public JProgressBar(int orient, int min, int max)
Creates a progress bar using the specified orientation, minimum, and maximum. By default, a border is painted but a progress string is not. Sets the initial value of the progress bar to the specified minimum. The BoundedRangeModel that holds the progress bar's data handles any issues that may arise from improperly setting the minimum, initial, and maximum values on the progress bar.

param
orient the desired orientation of the progress bar
param
min the minimum value of the progress bar
param
max the maximum value of the progress bar
see
BoundedRangeModel
see
#setOrientation
see
#setBorderPainted
see
#setStringPainted
see
#setString
see
#setIndeterminate

	// Creating the model this way is a bit simplistic, but
	//  I believe that it is the the most common usage of this
	//  component - it's what people will expect.
        setModel(new DefaultBoundedRangeModel(min, 0, min, max));
        updateUI();

        setOrientation(orient);      // documented with set/getOrientation()
        setBorderPainted(true);      // documented with is/setBorderPainted()
	setStringPainted(false);     // see setStringPainted
	setString(null);             // see getString
	setIndeterminate(false);     // see setIndeterminate
    
public JProgressBar(BoundedRangeModel newModel)
Creates a horizontal progress bar that uses the specified model to hold the progress bar's data. By default, a border is painted but a progress string is not.

param
newModel the data model for the progress bar
see
#setOrientation
see
#setBorderPainted
see
#setStringPainted
see
#setString
see
#setIndeterminate

        setModel(newModel);
        updateUI();

        setOrientation(defaultOrientation);  // see setOrientation()
        setBorderPainted(true);              // see setBorderPainted()
	setStringPainted(false);             // see setStringPainted
	setString(null);                     // see getString
	setIndeterminate(false);             // see setIndeterminate
    
Methods Summary
public voidaddChangeListener(javax.swing.event.ChangeListener l)
Adds the specified ChangeListener to the progress bar.

param
l the ChangeListener to add

        listenerList.add(ChangeListener.class, l);
    
protected javax.swing.event.ChangeListenercreateChangeListener()
Subclasses that want to handle change events from the model differently can override this to return an instance of a custom ChangeListener implementation.

see
#changeListener
see
javax.swing.event.ChangeListener
see
javax.swing.BoundedRangeModel

        return new ModelListener();
    
protected voidfireStateChanged()
Notifies all listeners that have registered interest in ChangeEvents. The event instance is created if necessary.

see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==ChangeListener.class) {
                // Lazily create the event:
                if (changeEvent == null)
                    changeEvent = new ChangeEvent(this);
                ((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
            }          
        }
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this JProgressBar. For progress bars, the AccessibleContext takes the form of an AccessibleJProgressBar. A new AccessibleJProgressBar instance is created if necessary.

return
an AccessibleJProgressBar that serves as the AccessibleContext of this JProgressBar
beaninfo
expert: true description: The AccessibleContext associated with this ProgressBar.

        if (accessibleContext == null) {
            accessibleContext = new AccessibleJProgressBar();
        }
        return accessibleContext;
    
public javax.swing.event.ChangeListener[]getChangeListeners()
Returns an array of all the ChangeListeners added to this progress bar with addChangeListener.

return
all of the ChangeListeners added or an empty array if no listeners have been added
since
1.4

        return (ChangeListener[])listenerList.getListeners(
                ChangeListener.class);
    
public intgetMaximum()
Returns the progress bar's maximum value, which is stored in the progress bar's BoundedRangeModel. By default, the maximum value is 100.

return
the progress bar's maximum value
see
#setMaximum
see
BoundedRangeModel#getMaximum

 return getModel().getMaximum(); 
public intgetMinimum()
Returns the progress bar's minimum value, which is stored in the progress bar's BoundedRangeModel. By default, the minimum value is 0.

return
the progress bar's minimum value
see
#setMinimum
see
BoundedRangeModel#getMinimum

 return getModel().getMinimum(); 
public javax.swing.BoundedRangeModelgetModel()
Returns the data model used by this progress bar.

return
the BoundedRangeModel currently in use
see
BoundedRangeModel

        return model;
    
public intgetOrientation()
Returns JProgressBar.VERTICAL or JProgressBar.HORIZONTAL, depending on the orientation of the progress bar. The default orientation is HORIZONTAL.

return
HORIZONTAL or VERTICAL
see
#setOrientation

        return orientation;
    
public doublegetPercentComplete()
Returns the percent complete for the progress bar. Note that this number is between 0.0 and 1.0.

return
the percent complete for this progress bar

	long span = model.getMaximum() - model.getMinimum();
	double currentValue = model.getValue();
	double pc = (currentValue - model.getMinimum()) / span;
	return pc;
    
public java.lang.StringgetString()
Returns the current value of the progress string. If you are providing a custom progress string by overriding this method, make sure your implementation calls setString before calling super.getString.

return
the value of the percent string
see
#setString

	if (progressString != null) {
	    return progressString;
	} else {
            if (format == null) {
                format = NumberFormat.getPercentInstance();
            }
            return format.format(new Double(getPercentComplete()));
        }
    
public javax.swing.plaf.ProgressBarUIgetUI()
Returns the look-and-feel object that renders this component.

return
the ProgressBarUI object that renders this component

        return (ProgressBarUI)ui;
    
public java.lang.StringgetUIClassID()
Returns the name of the look-and-feel class that renders this component.

return
the string "ProgressBarUI"
see
JComponent#getUIClassID
see
UIDefaults#getUI
beaninfo
expert: true description: A string that specifies the name of the look-and-feel class.

        return uiClassID;
    
public intgetValue()
Returns the progress bar's current value, which is stored in the progress bar's BoundedRangeModel. The value is always between the minimum and maximum values, inclusive. By default, the value is initialized to be equal to the minimum value.

return
the current value of the progress bar
see
#setValue
see
BoundedRangeModel#getValue

 return getModel().getValue(); 
public booleanisBorderPainted()
Returns the borderPainted property.

return
the value of the borderPainted property
see
#setBorderPainted
beaninfo
description: Does the progress bar paint its border

        return paintBorder;
    
public booleanisIndeterminate()
Returns the value of the indeterminate property.

return
the value of the indeterminate property
see
#setIndeterminate
since
1.4
beaninfo
description: Is the progress bar indeterminate (true) or normal (false)?

        return indeterminate;
    
public booleanisStringPainted()
Returns the value of the stringPainted property.

return
the value of the stringPainted property
see
#setStringPainted
see
#setString

        return paintString;
    
protected voidpaintBorder(java.awt.Graphics g)
Paints the progress bar's border if the borderPainted property is true.

param
g the Graphics context within which to paint the border
see
#paint
see
#setBorder
see
#isBorderPainted
see
#setBorderPainted

    
        if (isBorderPainted()) {
            super.paintBorder(g);
        }
    
protected java.lang.StringparamString()
Returns a string representation of this JProgressBar. This method is intended to be used only for debugging purposes. The content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

return
a string representation of this JProgressBar

	String orientationString = (orientation == HORIZONTAL ?
				    "HORIZONTAL" : "VERTICAL");
	String paintBorderString = (paintBorder ?
				    "true" : "false");
	String progressStringString = (progressString != null ?
				       progressString : "");
	String paintStringString = (paintString ?
				    "true" : "false");
	String indeterminateString = (indeterminate ?
				    "true" : "false");

	return super.paramString() +
	",orientation=" + orientationString +
	",paintBorder=" + paintBorderString +
	",paintString=" + paintStringString +
	",progressString=" + progressStringString +
	",indeterminateString=" + indeterminateString;
    
public voidremoveChangeListener(javax.swing.event.ChangeListener l)
Removes a ChangeListener from the progress bar.

param
l the ChangeListener to remove

        listenerList.remove(ChangeListener.class, l);
    
public voidsetBorderPainted(boolean b)
Sets the borderPainted property, which is true if the progress bar should paint its border. The default value for this property is true. Some look and feels might not implement painted borders; they will ignore this property.

param
b true if the progress bar should paint its border; otherwise, false
see
#isBorderPainted
beaninfo
bound: true attribute: visualUpdate true description: Whether the progress bar should paint its border.

        boolean oldValue = paintBorder;
        paintBorder = b;
        firePropertyChange("borderPainted", oldValue, paintBorder);
        if (paintBorder != oldValue) {
            repaint();
        }
    
public voidsetIndeterminate(boolean newValue)
Sets the indeterminate property of the progress bar, which determines whether the progress bar is in determinate or indeterminate mode. An indeterminate progress bar continuously displays animation indicating that an operation of unknown length is occurring. By default, this property is false. Some look and feels might not support indeterminate progress bars; they will ignore this property.

See How to Monitor Progress for examples of using indeterminate progress bars.

param
newValue true if the progress bar should change to indeterminate mode; false if it should revert to normal.
see
#isIndeterminate
see
javax.swing.plaf.basic.BasicProgressBarUI
since
1.4
beaninfo
bound: true attribute: visualUpdate true description: Set whether the progress bar is indeterminate (true) or normal (false).

	boolean oldValue = indeterminate;
	indeterminate = newValue;
	firePropertyChange("indeterminate", oldValue, indeterminate);
    
public voidsetMaximum(int n)
Sets the progress bar's maximum value (stored in the progress bar's data model) to n. The underlying BoundedRangeModel handles any mathematical issues arising from assigning faulty values.

If the maximum value is different from the previous maximum, all change listeners are notified.

param
n the new maximum
see
#getMaximum
see
#addChangeListener
see
BoundedRangeModel#setMaximum
beaninfo
preferred: true description: The progress bar's maximum value.

 getModel().setMaximum(n); 
public voidsetMinimum(int n)
Sets the progress bar's minimum value (stored in the progress bar's data model) to n. The data model (a BoundedRangeModel instance) handles any mathematical issues arising from assigning faulty values.

If the minimum value is different from the previous minimum, all change listeners are notified.

param
n the new minimum
see
#getMinimum
see
#addChangeListener
see
BoundedRangeModel#setMinimum
beaninfo
preferred: true description: The progress bar's minimum value.

 getModel().setMinimum(n); 
public voidsetModel(javax.swing.BoundedRangeModel newModel)
Sets the data model used by the JProgressBar.

param
newModel the BoundedRangeModel to use
beaninfo
expert: true description: The data model used by the JProgressBar.

        // PENDING(???) setting the same model to multiple bars is broken; listeners
        BoundedRangeModel oldModel = getModel();

        if (newModel != oldModel) {
            if (oldModel != null) {
                oldModel.removeChangeListener(changeListener);
                changeListener = null;
            }

            model = newModel;

            if (newModel != null) {
                changeListener = createChangeListener();
                newModel.addChangeListener(changeListener);
            }

	    if (accessibleContext != null) {
                accessibleContext.firePropertyChange(
		        AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
                        (oldModel== null 
			 ? null : new Integer(oldModel.getValue())),
                        (newModel== null 
			 ? null : new Integer(newModel.getValue())));
	    }

	    if (model != null) {
		model.setExtent(0);
	    }
            repaint();
        }
    
public voidsetOrientation(int newOrientation)
Sets the progress bar's orientation to newOrientation, which must be JProgressBar.VERTICAL or JProgressBar.HORIZONTAL. The default orientation is HORIZONTAL.

param
newOrientation HORIZONTAL or VERTICAL
exception
IllegalArgumentException if newOrientation is an illegal value
see
#getOrientation
beaninfo
preferred: true bound: true attribute: visualUpdate true description: Set the progress bar's orientation.

        if (orientation != newOrientation) {
            switch (newOrientation) {
            case VERTICAL:
            case HORIZONTAL:
                int oldOrientation = orientation;
                orientation = newOrientation;
                firePropertyChange("orientation", oldOrientation, newOrientation);
                if (accessibleContext != null) {
                    accessibleContext.firePropertyChange(
			    AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
                            ((oldOrientation == VERTICAL) 
			     ? AccessibleState.VERTICAL 
			     : AccessibleState.HORIZONTAL),
                            ((orientation == VERTICAL) 
			     ? AccessibleState.VERTICAL 
			     : AccessibleState.HORIZONTAL));
	        }
                break;
            default:
                throw new IllegalArgumentException(newOrientation +
                                             " is not a legal orientation");
            }
            revalidate();
        }
    
public voidsetString(java.lang.String s)
Sets the value of the progress string. By default, this string is null. If you have provided a custom progress string and want to revert to the built-in behavior, set the string back to null. If you are providing a custom progress string by overriding this method, make sure that you call setString before calling getString. The progress string is painted only if the isStringPainted method returns true.

param
s the value of the percent string
see
#getString
see
#setStringPainted
see
#isStringPainted
beaninfo
bound: true attribute: visualUpdate true description: Specifies the progress string to paint

        String oldValue = progressString;
	progressString = s;
        firePropertyChange("string", oldValue, progressString);
        if (progressString == null || oldValue == null || !progressString.equals(oldValue)) {
	    repaint();
        }
    
public voidsetStringPainted(boolean b)
Sets the value of the stringPainted property, which determines whether the progress bar should render a progress string. The default is false: no string is painted. Some look and feels might not support progress strings or might support them only when the progress bar is in determinate mode.

param
b true if the progress bar should render a string
see
#isStringPainted
see
#setString
beaninfo
bound: true attribute: visualUpdate true description: Whether the progress bar should render a string.

        //PENDING: specify that string not painted when in indeterminate mode?
	//         or just leave that to the L&F?
        boolean oldValue = paintString;
        paintString = b;
        firePropertyChange("stringPainted", oldValue, paintString);
        if (paintString != oldValue) {
	    revalidate();
            repaint();
        }
    
public voidsetUI(javax.swing.plaf.ProgressBarUI ui)
Sets the look-and-feel object that renders this component.

param
ui a ProgressBarUI object
see
UIDefaults#getUI
beaninfo
bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.

        super.setUI(ui);
    
public voidsetValue(int n)
Sets the progress bar's current value (stored in the progress bar's data model) to n. The data model (a BoundedRangeModel instance) handles any mathematical issues arising from assigning faulty values.

If the new value is different from the previous value, all change listeners are notified.

param
n the new value
see
#getValue
see
BoundedRangeModel#setValue
beaninfo
preferred: true description: The progress bar's current value.

 
        BoundedRangeModel brm = getModel();
	int oldValue = brm.getValue();
	brm.setValue(n);
 
	if (accessibleContext != null) {
            accessibleContext.firePropertyChange(
		    AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
                    new Integer(oldValue),
                    new Integer(brm.getValue()));
	}
    
public voidupdateUI()
Resets the UI property to a value from the current look and feel.

see
JComponent#updateUI

        setUI((ProgressBarUI)UIManager.getUI(this));
    
private voidwriteObject(java.io.ObjectOutputStream s)
See readObject() and writeObject() in JComponent for more information about serialization in Swing.

        s.defaultWriteObject();
        if (getUIClassID().equals(uiClassID)) {
            byte count = JComponent.getWriteObjCounter(this);
            JComponent.setWriteObjCounter(this, --count);
            if (count == 0 && ui != null) {
                ui.installUI(this);
            }
        }