Class MultiProgressDialog
- All Implemented Interfaces:
ImageObserver,MenuContainer,Serializable,Accessible,RootPaneContainer,WindowConstants
USAGE: Start by extending one of the worker classes: either MultiProgressWorker (for major and minor progress) or SimpleProgressWorker (for just a single progress bar). Implement the run() method to perform your long-running task. As your task progresses, invoke the various fire...() methods to notify listeners of progress. Remember to invoke either fireProgressComplete() or fireProgressCanceled() at the end of your run() method to let listeners know that the work is done. Failure to invoke one of these termination events will result in the progress dialog remaining open indefinitely.
When you have your worker class ready, create an instance of MultiProgressDialog, and invoke its runWorker() method, passing in an instance of your worker class. If you wish to set other options (documented below), do so before invoking runWorker().
MultiProgressDialog instances can be re-used, but be sure to invoke resetProgress() in between each usage to reset the progress bars.
Other options
- You can set an initial show delay on the dialog, so that it will only appear if the work takes longer than a certain amount of time. This is useful to avoid flashing a progress dialog for very short operations. Use the setInitialShowDelayMS() method to set this delay time in milliseconds. The default is 0, meaning the dialog will appear as soon as the work begins.
- You can customize the format of the progress messages shown in the major and minor progress labels. See the DEFAULT_PROGRESS_FORMAT constant for details. Use the setFormatString() method to change the format string.
- Since:
- swing-extras 1.6 (2022-04-15)
- Author:
- scorbo2
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumLong progress messages are truncated at a fixed length to avoid rendering problems with very large JLabels on the dialog.Nested classes/interfaces inherited from class javax.swing.JDialog
JDialog.AccessibleJDialogNested classes/interfaces inherited from class java.awt.Dialog
Dialog.AccessibleAWTDialog, Dialog.ModalExclusionType, Dialog.ModalityTypeNested classes/interfaces inherited from class java.awt.Window
Window.AccessibleAWTWindow, Window.TypeNested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainerNested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThis will yield: "[%currentStep of %totalSteps] %message"static final StringIf you really don't like the new 2.7 default format, you can use this legacy format string to get the old behavior.Fields inherited from class javax.swing.JDialog
accessibleContext, rootPane, rootPaneCheckingEnabledFields inherited from class java.awt.Dialog
DEFAULT_MODALITY_TYPEFields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTHFields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, EXIT_ON_CLOSE, HIDE_ON_CLOSE -
Constructor Summary
ConstructorsConstructorDescriptionMultiProgressDialog(Window owner, String title) Creates a new, blank MultiProgressDialog with the specified owner window and window title. -
Method Summary
Modifier and TypeMethodDescriptionReturns the current format string that will be used to display progress messages.longReturns the optional delay time, in milliseconds, between the time when the work begins and the time when the progress dialog is made visible.Returns the current truncation mode for long progress messages.booleanIndicates whether the cancel button has been clicked or not.voidResets to a blank, default state.voidrunWorker(MultiProgressWorker worker, boolean disposeWhenComplete) Executes the given Runnable and auto-wires all progress events to this dialog.voidrunWorker(SimpleProgressWorker worker, boolean disposeWhenComplete) Executes the given Runnable and auto-wires all progress events to this dialog.voidsetFormatString(String formatString) Optionally change the format string that will be used to display progress messages.voidsetInitialShowDelayMS(long initialShowDelayMS) Sets an optional delay time, in milliseconds, between the time when the work starts and the time when the dialog will make itself visible.voidsetMajorProgress(int progress) Sets the progress value for the major progress bar without updating the progress label.voidsetMajorProgress(int progress, String message) Sets the progress value for the major progress bar and updates the major progress label with the given message.voidsetMajorProgressBounds(int minimum, int maximum) Sets the minimum and maximum bounds of the major progress bar.This will also set the major progress value to "minimum".voidsetMinorProgress(int progress) Sets the progress value for the minor progress bar without updating the progress label.voidsetMinorProgress(int progress, String message) Sets the progress value for the minor progress bar and updates the major progress label with the given message.voidsetMinorProgressBounds(int minimum, int maximum) Sets the minimum and maximum bounds of the minor progress bar.This will also set the minor progress value to "minimum".voidsetTruncationMode(MultiProgressDialog.TruncationMode truncationMode) The default behavior is to truncate long progress messages at the end.Methods inherited from class javax.swing.JDialog
addImpl, createRootPane, dialogInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, updateMethods inherited from class java.awt.Dialog
addNotify, getModalityType, getTitle, hide, isModal, isResizable, isUndecorated, setBackground, setModal, setModalityType, setOpacity, setResizable, setShape, setTitle, setUndecorated, setVisible, show, toBackMethods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBackground, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOpacity, getOwnedWindows, getOwner, getOwnerlessWindows, getShape, getToolkit, getType, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isAutoRequestFocus, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isOpaque, isShowing, isValidateRoot, pack, paint, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeNotify, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setAutoRequestFocus, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImage, setIconImages, setLocation, setLocation, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setType, toFrontMethods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusDownCycle, validate, validateTreeMethods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, requestFocusInWindow, resize, resize, revalidate, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setMaximumSize, setMixingCutoutShape, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Field Details
-
DEFAULT_PROGRESS_FORMAT
This will yield: "[%currentStep of %totalSteps] %message"You can go back to the pre-2.7 format with "%m (%s of %t)", which will yield "%message (%currentStep of %totalSteps)".
It's probably best to keep the "x of y" part on the left side of the string. The string length of "%message" can vary widely and rapidly as progress continues, which can make it hard to read the step counts if they're bouncing around at the end of the string.
But rather than hard-coding a "fix" for that problem, it is now configurable!
The available tags are:
- %m - The progress message sent from the worker thread
- %s - The current step number (1-based)
- %t - The total number of steps
You can add whatever punctuation, spacing, or other text you like around the tags, though be aware there is a length limit on the progress label, and the worker-supplied message can be quite long.
Use the setFormatString() method to change the format string.
- See Also:
-
LEGACY_PROGRESS_FORMAT
If you really don't like the new 2.7 default format, you can use this legacy format string to get the old behavior.- See Also:
-
-
Constructor Details
-
MultiProgressDialog
Creates a new, blank MultiProgressDialog with the specified owner window and window title. Closing the progress dialog will act the same as though the cancel button had been clicked. Call isCanceled() at any time to see if the operation should continue or not (that is, if the user has clicked the cancel button on the progress dialog).- Parameters:
owner- The Window that will own this MultiProgressDialogtitle- The window title
-
-
Method Details
-
resetProgress
public void resetProgress()Resets to a blank, default state. Also resets the isCanceled flag. -
getInitialShowDelayMS
public long getInitialShowDelayMS()Returns the optional delay time, in milliseconds, between the time when the work begins and the time when the progress dialog is made visible. The default value is 0, meaning the dialog will appear as soon as the work begins. -
setInitialShowDelayMS
public void setInitialShowDelayMS(long initialShowDelayMS) Sets an optional delay time, in milliseconds, between the time when the work starts and the time when the dialog will make itself visible. The default value is 0, which means the dialog will appear as soon as the work begins. But you can set this to avoid showing a dialog for very short-running tasks. For example, setting this value to 2000 will prevent the dialog from showing if the work to be executed completes in less than 2 seconds. -
runWorker
Executes the given Runnable and auto-wires all progress events to this dialog. This is a very easy way to simply implement some runnable that can fire progress events, and pass it to this method to handle the UI aspect automatically. Progress errors are simply ignored here. You can add your own MultiProgressAdapter to the worker before passing it in here if you wish to respond to errors. This method will show both major and minor progress bars. It is intended for complex tasks that have subtasks. Use the overloaded runWorker that accepts a SimpleProgressWorker if you only need a single progress bar.- Parameters:
worker- Any MultiProgressWorker implementation that can perform some task.disposeWhenComplete- , if true, will dispose() this dialog when complete. Otherwise, hides the dialog.
-
runWorker
Executes the given Runnable and auto-wires all progress events to this dialog. This is a very easy way to simply implement some runnable that can fire progress events, and pass it to this method to handle the UI aspect automatically. Progress errors are simply ignored here. You can add your own SimpleProgressAdapter to the worker before passing it in here if you wish to respond to errors. This method will hide the "minor" progress bar and only show a single progress bar. It is intended for simple tasks. Use the overloaded runWorker that accepts a MultiProgressWorker to show both major and minor progress.- Parameters:
worker- Any SimpleProgressWorker implementation that can perform some task.disposeWhenComplete- , if true, will dispose() this dialog when complete. Otherwise, hides the dialog.
-
setMajorProgressBounds
public void setMajorProgressBounds(int minimum, int maximum) Sets the minimum and maximum bounds of the major progress bar.This will also set the major progress value to "minimum".- Parameters:
minimum- The minimum value of the major progress bar (typically 0).maximum- The maximum value of the major progress bar.
-
setMinorProgressBounds
public void setMinorProgressBounds(int minimum, int maximum) Sets the minimum and maximum bounds of the minor progress bar.This will also set the minor progress value to "minimum".- Parameters:
minimum- The minimum value of the minor progress bar (typically 0).maximum- The maximum value of the minor progress bar.
-
setMajorProgress
public void setMajorProgress(int progress) Sets the progress value for the major progress bar without updating the progress label. See also setMajorProgress(int,String)- Parameters:
progress- The new value for the major progress bar.
-
setMajorProgress
Sets the progress value for the major progress bar and updates the major progress label with the given message.- Parameters:
progress- The new value for the major progress bar.message- The new message to show in the major progress label (ignored if null).
-
setMinorProgress
public void setMinorProgress(int progress) Sets the progress value for the minor progress bar without updating the progress label. See also setMajorProgress(int,String)- Parameters:
progress- The new value for the minor progress bar.
-
setMinorProgress
Sets the progress value for the minor progress bar and updates the major progress label with the given message.- Parameters:
progress- The new value for the minor progress bar.message- The new message to show in the minor progress label (ignored if null).
-
isCanceled
public boolean isCanceled()Indicates whether the cancel button has been clicked or not.- Returns:
- True if the cancel button has been clicked.
-
getFormatString
Returns the current format string that will be used to display progress messages. See the DEFAULT_PROGRESS_FORMAT constant for details. -
setFormatString
Optionally change the format string that will be used to display progress messages. See the DEFAULT_PROGRESS_FORMAT constant for details. -
getTruncationMode
Returns the current truncation mode for long progress messages. -
setTruncationMode
The default behavior is to truncate long progress messages at the end. You can change this to truncate at the start instead. Example: "some unreasonably long message" can either become "some unreasonably long mes..." with TruncationMode.END, or it can become "...nably long message" with TruncationMode.START.
-