Class OptionPanel
- All Implemented Interfaces:
ImageObserver,MenuContainer,Serializable,Accessible
JCheckBoxes) in a
multi-column layout suitable for use in MDI views.
Option Data Format
Options are specified as an array of three-element String arrays:
{ { "Option 1", "true", "false" },
{ "Option 2", "true", "true" },
{ "Option 3", "false", "false" } }
Each inner array must contain exactly three elements:
- label – the text shown beside the checkbox (index 0)
- enabled –
"true"or"false"(index 1) - selected–
"true"or"false"(index 2)
Layout
Checkboxes are distributed across the requested number of columns in
column-major order (filled top-to-bottom, then left-to-right). Three
ordering modes are available via the layoutOption constructor
parameter:
AS_ORDERED– options appear in the order suppliedALPHABETICAL– options are sorted by label (case-insensitive)MINSIZE– options are sorted so the widest labels are spread across columns, minimising overall panel width
Each column is only as wide as its widest checkbox. Columns are separated by
HGAP pixels, and rows are spaced by font-height plus VGAP
pixels.
Preferred-size and borders
Layout is performed once at construction time using a null layout (absolute
positioning). The content size (the area required by the checkboxes
themselves, excluding any border insets) is captured in
_contentSize. getPreferredSize() then adds the panel's
current insets to that content size each time it is called, so the
result is always correct even when a border — such as a
CommonBorder — is applied after construction (which would
otherwise cause the border's title area to be clipped).
Thread safety
This class is not thread-safe. All interactions must occur on the Swing Event Dispatch Thread (EDT).
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceCallback interface for changes to checkbox selection state within anOptionPanel.Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanelNested 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 intLayout option: sort options alphabetically by label (case-insensitive) before laying them out in columns.static final intLayout option: display options in the order they were supplied to the constructor, with no reordering.static final intHorizontal gap in pixels between adjacent columns of checkboxes.static final intLayout option: sort options by descending label pixel width before laying them out in columns.static final intAdditional vertical gap in pixels added to the font height to determine the height of each row.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, WIDTH -
Constructor Summary
ConstructorsConstructorDescriptionOptionPanel(OptionPanel.OptionPanelListener listener, int columnCount, Font font, Color foreground, Color background, int layoutOption, String[][] optionData) Creates anOptionPanelwith the specified configuration. -
Method Summary
Modifier and TypeMethodDescriptionvoiddoLayout()Positions each checkbox using the panel's current insets as the content origin.getCheckBox(String label) Returns the underlyingJCheckBoxfor the option identified bylabel, ornullif no such option exists.Returns the preferred size of this panel, dynamically adding the panel's current border insets to the pre-computed content size.String[]Returns the labels of all currently selected options, in the order they were originally supplied to the constructor.booleanisOptionSelected(String label) Returns whether the option identified bylabelis currently selected.voidsetOptionEnabled(String label, boolean enabled) Enables or disables the checkbox identified bylabel.voidsetOptionSelected(String label, boolean selected) Programmatically sets the selected state of the checkbox identified bylabel.Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, 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, 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, paintBorder, 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, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, 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, setLayout, 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
-
AS_ORDERED
public static final int AS_ORDEREDLayout option: display options in the order they were supplied to the constructor, with no reordering.- See Also:
-
ALPHABETICAL
public static final int ALPHABETICALLayout option: sort options alphabetically by label (case-insensitive) before laying them out in columns.- See Also:
-
MINSIZE
public static final int MINSIZELayout option: sort options by descending label pixel width before laying them out in columns. This tends to produce the narrowest overall panel width because the widest labels are distributed evenly across columns rather than all ending up in the same one.- See Also:
-
HGAP
public static final int HGAPHorizontal gap in pixels between adjacent columns of checkboxes. Callers who need a different gap should subclass or wrap the panel.- See Also:
-
VGAP
public static final int VGAPAdditional vertical gap in pixels added to the font height to determine the height of each row.- See Also:
-
-
Constructor Details
-
OptionPanel
public OptionPanel(OptionPanel.OptionPanelListener listener, int columnCount, Font font, Color foreground, Color background, int layoutOption, String[][] optionData) Creates anOptionPanelwith the specified configuration.Layout is performed immediately during construction. If a border will be added after construction (e.g. in a subclass),
getPreferredSize()will still return the correct size because it adds the current insets dynamically rather than relying on a snapshot taken at construction time.- Parameters:
listener- callback notified when any checkbox changes state;nullis permitted and means no notificationcolumnCount- desired number of columns; must be ≥ 1font- font used for all checkbox labels; must not benullforeground- foreground (text) colour for labels;nulluses the look-and-feel defaultbackground- background colour for the panel and all checkboxes;nulluses the look-and-feel default and leaves the panel non-opaquelayoutOption- ordering mode; one ofAS_ORDERED,ALPHABETICAL, orMINSIZEoptionData- option specifications; each element must be a three-element array{label, enabled, selected}- Throws:
IllegalArgumentException- ifcolumnCount < 1,fontisnull,optionDataisnull, or any inner array has fewer than three elements
-
-
Method Details
-
getPreferredSize
Returns the preferred size of this panel, dynamically adding the panel's current border insets to the pre-computed content size.Because insets are read at call time rather than snapshotted at construction time, this method returns a correct value even when a border (e.g. a
CommonBorder) is applied after the constructor returns — a pattern used by subclasses such asChimeraOptionPanel.- Overrides:
getPreferredSizein classJComponent- Returns:
- the preferred
Dimension; nevernull
-
doLayout
public void doLayout()Positions each checkbox using the panel's current insets as the content origin.Because this method is called by Swing every time the component is validated — including after a border is applied post-construction — the checkboxes are always placed below the titled border's title text and inside any other inset region, regardless of when
Borderwas set.The column/row assignments and column widths computed by
layoutEntries()are reused here; only the pixel coordinates are recalculated. -
isOptionSelected
Returns whether the option identified bylabelis currently selected.- Parameters:
label- the label of the option to query; must not benull- Returns:
trueif the option exists and its checkbox is selected;falseotherwise (including when the label is not found)
-
setOptionSelected
Programmatically sets the selected state of the checkbox identified bylabel.If the label is not found, this method does nothing. The call will fire any registered
OptionPanel.OptionPanelListener(via the checkbox's ownItemListener) if the state actually changes.- Parameters:
label- the label of the option to update; must not benullselected-trueto select,falseto deselect
-
setOptionEnabled
Enables or disables the checkbox identified bylabel.A disabled checkbox is visible but cannot be interacted with by the user. If the label is not found, this method does nothing.
- Parameters:
label- the label of the option to update; must not benullenabled-trueto enable,falseto disable
-
getSelectedOptionLabels
Returns the labels of all currently selected options, in the order they were originally supplied to the constructor.- Returns:
- a new array containing the labels of all selected options;
never
null, but may be empty
-
getCheckBox
Returns the underlyingJCheckBoxfor the option identified bylabel, ornullif no such option exists.This method is intended for advanced customisation (e.g. attaching additional listeners or tweaking renderer properties). Prefer the higher-level methods (
isOptionSelected(java.lang.String),setOptionSelected(java.lang.String, boolean), etc.) for normal use.- Parameters:
label- the label of the option; must not benull- Returns:
- the
JCheckBox, ornullif the label is not found
-