Class AToolBar
- All Implemented Interfaces:
ImageObserver,MenuContainer,Serializable,Accessible,SwingConstants
- Direct Known Subclasses:
BaseToolBar
JToolBar for toolbars that contain a mutually exclusive
set of JToggleButtons (i.e., a radio-button-like group), plus optional
one-shot buttons.
This class manages:
- a primary
ButtonGroupthat enforces mutual exclusivity - an optional default toggle button (selected when the active toggle is turned off)
- a selection-change hook for subclasses
- a registry of buttons by stable id for programmatic enable/disable
Button registry
Toolbars often need to enable/disable specific tools depending on application state (e.g., disable Delete when nothing is selected). Rather than forcing applications to keep references to every button instance, this class supports registering buttons under a stable string id and retrieving them later:
toolBar.setButtonEnabled("delete", hasSelection);
toolBar.getButton("pointer", JToggleButton.class).setSelected(true);
For predefined buttons, you typically use ToolBits.getId(long) as
the stable id. For application-defined buttons, choose your own ids.
Notes
- You may still add non-toggle components (regular buttons, separators,
etc.) using
Container.add(Component)fromJToolBar. - Only toggles added via
addToggle(JToggleButton, boolean)are managed by the primary group. - The registry is populated by using the id-aware overloads
addToggle(String, JToggleButton)/addButton(String, JButton). If you callContainer.add(Component)directly, you may register manually viaregisterButton(String, AbstractButton).
- Author:
- heddle
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.JToolBar
JToolBar.AccessibleJToolBar, JToolBar.SeparatorNested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponentNested 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 StringClient property key used to store an id on a button.protected JTextFieldStatus field to display messages (may be null).protected final ButtonGroupPrimary mutually-exclusive group for tool toggle buttons.Fields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class java.awt.Component
accessibleContext, 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.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected abstract voidactiveToggleButtonChanged(JToggleButton newlyActive) Called when the active toggle button in the primary group changes.Add a button to the toolbar and register it under the given id.addToggle(String id, JToggleButton toggleButton) Add a toggle to the toolbar and register it under the given id.addToggle(String id, JToggleButton toggleButton, boolean toGroup) Add a toggle button to the toolbar, optionally adding it to the primary mutually-exclusive group, and register it under the given id.addToggle(JToggleButton toggleButton, boolean toGroup) Add a toggle button to the toolbar, optionally adding it to the primary mutually-exclusive group.Return the currently selected toggle button from the primary group.Look up a registered toolbar button by id.<T extends AbstractButton>
TLook up a registered toolbar button by id and expected type.Get the default toggle button (if any).static StringgetToolId(AbstractButton button) Try to read the registered tool id from a button.booleanCheck if this toolbar has a status field.protected <T extends AbstractButton>
TregisterButton(String id, T button) Register a toolbar button under a stable id.registerExternalToggle(String id, JToggleButton toggleButton) Registers an external toggle button with this toolbar's primary toggle group without adding the button to the toolbar component hierarchy.removeButton(String id) Remove a registered button from the registry by id.voidremoveToggle(JToggleButton toggleButton) Remove a toggle button from the toolbar and from the primary group.<T extends AbstractButton>
TrequireButton(String id, Class<T> type) Look up a registered toolbar button by id, throwing if missing.voidProgrammatically select the default toggle button.booleansetButtonEnabled(String id, boolean enabled) Enable or disable a registered button by id.voidsetDefaultToggleButton(JToggleButton defaultToggleButton) Set the default toggle button.voidspacer(int pixels) Add a spacer of the given size in pixels.voidupdateStatusText(String text) Set the status text shown on the toolbar.Methods inherited from class javax.swing.JToolBar
add, addImpl, addSeparator, addSeparator, createActionChangeListener, createActionComponent, getAccessibleContext, getComponentAtIndex, getComponentIndex, getMargin, getOrientation, getUI, getUIClassID, isBorderPainted, isFloatable, isRollover, paintBorder, paramString, setBorderPainted, setFloatable, setLayout, setMargin, setOrientation, setRollover, setUI, updateUIMethods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateMethods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, 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, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Field Details
-
CLIENTPROP_TOOL_ID
Client property key used to store an id on a button.- See Also:
-
toggleGroup
Primary mutually-exclusive group for tool toggle buttons. -
statusField
Status field to display messages (may be null).
-
-
Constructor Details
-
AToolBar
public AToolBar()Create a toolbar with horizontal orientation. -
AToolBar
public AToolBar(int orientation) Create a toolbar with the given orientation.- Parameters:
orientation-SwingConstants.HORIZONTALorSwingConstants.VERTICAL.
-
-
Method Details
-
registerButton
Register a toolbar button under a stable id.This is used by the id-aware add methods. It is also safe for subclasses to call directly if they add components via
Container.add(Component).For debugging and tooling, this method also sets:
Component.setName(String)to the idbutton.putClientProperty("toolId", id)
- Parameters:
id- stable identifier (non-blank).button- the button to register.- Returns:
- the same button (for chaining).
- Throws:
NullPointerException- if id or button is null.IllegalArgumentException- if id is blank or already used by a different button.
-
removeButton
Remove a registered button from the registry by id.This does not remove the button from the Swing component hierarchy. If you dynamically remove tools, call this in addition to
Container.remove(Component).- Parameters:
id- the id to remove (null/blank are ignored).- Returns:
- the removed button, or
nullif none was registered.
-
getButton
Look up a registered toolbar button by id.- Parameters:
id- the id used when adding/registering the button.- Returns:
- the button, or
nullif not found.
-
getButton
Look up a registered toolbar button by id and expected type.- Type Parameters:
T- type parameter.- Parameters:
id- the id used when adding/registering the button.type- expected type.- Returns:
- the typed button, or
nullif not found or wrong type.
-
requireButton
Look up a registered toolbar button by id, throwing if missing.This is handy in application wiring code where missing tools should be a programming error rather than silently ignored.
- Type Parameters:
T- type parameter.- Parameters:
id- registered id (non-blank).type- expected type.- Returns:
- the typed button (never null).
- Throws:
IllegalStateException- if no button exists under that id, or the type is wrong.
-
setButtonEnabled
Enable or disable a registered button by id.- Parameters:
id- button id.enabled- new enabled state.- Returns:
trueif the button was found and updated,falseif no button is registered under that id.
-
getToolId
Try to read the registered tool id from a button.- Parameters:
button- a button that may have been registered.- Returns:
- the id string, or
nullif not present.
-
registerExternalToggle
Registers an external toggle button with this toolbar's primary toggle group without adding the button to the toolbar component hierarchy.This is useful for palette buttons that should behave like tools and be mutually exclusive with toolbar toggles, while remaining visually located outside the toolbar.
- Parameters:
id- stable identifier for the external tooltoggleButton- external toggle button- Returns:
- the same toggle button
-
getButtonRegistryView
- Returns:
- an unmodifiable view of the current button registry.
-
addButton
Add a button to the toolbar and register it under the given id.- Parameters:
id- stable identifier for later retrieval (non-blank).button- the button to add.- Returns:
- the added button (for chaining).
- Throws:
NullPointerException- if id or button is null.IllegalArgumentException- if id is blank or already used.
-
addToggle
Add a toggle to the toolbar and register it under the given id.- Parameters:
id- stable identifier for later retrieval (non-blank).toggleButton- the toggle to add.- Returns:
- the added toggle (for chaining).
-
addToggle
Add a toggle button to the toolbar, optionally adding it to the primary mutually-exclusive group.- Parameters:
toggleButton- the toggle to add.toGroup- if true, add to the primary mutually-exclusive group.- Returns:
- the added toggle.
-
addToggle
Add a toggle button to the toolbar, optionally adding it to the primary mutually-exclusive group, and register it under the given id.- Parameters:
id- stable identifier for later retrieval (non-blank).toggleButton- the toggle to add.toGroup- if true, add to the primary mutually-exclusive group.- Returns:
- the added toggle (for chaining).
- Throws:
NullPointerException- if id or toggleButton is null.IllegalArgumentException- if id is blank or already used.
-
removeToggle
Remove a toggle button from the toolbar and from the primary group.- Parameters:
toggleButton- the toggle to remove (ignored if null).
-
activeToggleButtonChanged
Called when the active toggle button in the primary group changes.Subclasses override this to react to a tool selection change.
- Parameters:
newlyActive- the button that just became selected (never null).
-
getDefaultToggleButton
Get the default toggle button (if any).- Returns:
- the default toggle button, or null.
-
setDefaultToggleButton
Set the default toggle button.- Parameters:
defaultToggleButton- the default toggle (may be null).- Throws:
IllegalArgumentException- if the button is not null but not contained in this toolbar (it should be added first).
-
resetDefaultToggleButton
public void resetDefaultToggleButton()Programmatically select the default toggle button.If another toggle is currently active, it will be deselected by the
ButtonGroup. If no default is set, this method does nothing. -
getActiveButton
Return the currently selected toggle button from the primary group.- Returns:
- the selected toggle, or null if none is selected.
-
updateStatusText
Set the status text shown on the toolbar.- Parameters:
text- the status text to set.
-
hasStatusField
public boolean hasStatusField()Check if this toolbar has a status field.- Returns:
- true if this toolbar has a status field, false if not.
-
spacer
public void spacer(int pixels) Add a spacer of the given size in pixels.- Parameters:
pixels- the size of the spacer in pixels.
-