Class FormPanel
- All Implemented Interfaces:
ImageObserver,MenuContainer,Serializable,Accessible
- Layout management - you don't need to write manual GridBagLayout code to use a FormPanel. Just add your FormFields to the panel and the layout will be handled automatically.
- Form validation - assuming you've added FieldValidator instances to your FormFields as needed, you don't need to write much manual validation code, and you don't need to write any UI code to show validation results. Just call validateForm() or isFormValid(), and the validators will be invoked automatically.
- Optional inline help - every FormField can have optional help text which the FormPanel will render inline in the form of an information icon next to the field, which will show tooltip help text.
- Generic FormField handling - the FormField class is highly extensible, so you can very easily provide your own FormField implementation for custom display and editing of data.
Handling oversized forms
You can easily add a FormPanel to a JScrollPane to provide for scrollbars in the case where the form is unreasonably large.
Alignment
The Alignment property of the FormPanel controls how the entire form is aligned within the panel. You can choose left, center, or right horizontal alignment, and top, center, or bottom vertical alignment.
Additionally, the setBorderMargin() method allows you to specify extra pixel margins around the entire form, to keep it away from the edges of its container.
More documentation
The swing-extras-book contains much more documentation regarding the use of FormPanel, FormField, and related classes. Additionally, the built-in demo application showcases many of the features of this library.
- Since:
- 2019-11-24
- Author:
- scorbo2
- See Also:
-
Nested Class Summary
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 intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intFields 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
Constructors -
Method Summary
Modifier and TypeMethodDescriptionAdds the specified FormField to this FormPanel.Synonym for addAll(List<FormField> fields).Adds the specified list of FormFields to this FormPanel.Invoke this to clear the validation label off any previously validated field.findFormField(String identifier) Synonym for getFormField(String identifier).Deprecated, for removal: This API element is subject to removal in a future version.As of swing-extras 2.7.Returns the Alignment property of this FormPanel.Returns the optional border margin to be applied as described in setBorderMargin.intReturns the number of FormFields contained in this panel.getFormField(String identifier) Finds and returns a specific FormField by its identifier, if it exists.Returns a copy of the list of FormFields contained in this panel.intReturns the extra top margin, in pixels, that will be applied to multi-line field labels to better align them with their associated field components.booleanValidates each FormField by invoking all FieldValidators that are attached to it, then returns the overall result.voidOverridden here so we can also remove all FormField instances.Removes all FormFields from this FormPanel and re-renders it.setAlignment(Alignment alignment) Changes the Alignment property of this FormPanel and re-renders it.setBorderMargin(int margin) An optional pixel margin for the FormPanel itself to keep it away from the edges of its container.setBorderMargin(Margins margins) Sets optional pixel margins for the FormPanel itself to keep it away from the edges of its container.voidsetEnabled(boolean enabled) Overridden here so we can enable/disable all FormField instances when we receive a setEnabled request.setMultiLineFieldExtraTopMargin(int multiLineFieldExtraTopMargin) There's a very slight misalignment issue with field labels on multi-line FormField implementations due to the way GridBagLayout anchors components.Shorthand for isFormValid()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, 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, 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, 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, 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, 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
-
LEFT_SPACER_COLUMN
public static final int LEFT_SPACER_COLUMN- See Also:
-
LABEL_COLUMN
public static final int LABEL_COLUMN- See Also:
-
FORM_FIELD_START_COLUMN
public static final int FORM_FIELD_START_COLUMN- See Also:
-
CONTROL_COLUMN
public static final int CONTROL_COLUMN- See Also:
-
HELP_COLUMN
public static final int HELP_COLUMN- See Also:
-
VALIDATION_COLUMN
public static final int VALIDATION_COLUMN- See Also:
-
RIGHT_SPACER_COLUMN
public static final int RIGHT_SPACER_COLUMN- See Also:
-
-
Constructor Details
-
FormPanel
public FormPanel()Creates a new, empty FormPanel with TOP_CENTER Alignment. -
FormPanel
Creates a new, empty FormPanel with the given Alignment.
-
-
Method Details
-
setBorderMargin
An optional pixel margin for the FormPanel itself to keep it away from the edges of its container. The default value is zero, meaning no extra margins will be applied. Note that any value given here is added to whatever margins are already present on each individual FormField. This value does not replace those values. So, you can still indent a FormField from the others by setting its left margin on a left-aligned form, even if the FormPanel itself already specifies a border margin. The two values are added together in that case.- Parameters:
margin- The margin, in pixels, to apply to the FormPanel. Negative values are treated as 0.- Returns:
- This FormPanel instance, to allow method chaining.
-
setBorderMargin
Sets optional pixel margins for the FormPanel itself to keep it away from the edges of its container. The default value is zero, meaning no extra margins will be applied. Note that any value given here is added to whatever margins are already present on each individual FormField. This value does not replace those values. So, you can still indent a FormField from the others by setting its left margin on a left-aligned form, even if the FormPanel itself already specifies a border margin. The two values are added together in that case.Note: the Margins class defines an internalSpacing property. That property is ignored for FormPanel margin calculations. We only care about top, left, bottom, and right. "internalSpacing" is only relevant within individual FormField instances.
- Parameters:
margins- The Margins instance defining the margins to apply. Negative values are treated as 0.- Returns:
- This FormPanel instance, to allow method chaining.
-
getBorderMargin
Returns the optional border margin to be applied as described in setBorderMargin. The actual instance is returned, so callers can modify individual properties. -
getFormFields
Returns a copy of the list of FormFields contained in this panel. A copy of the list is returned to avoid client modification of the list itself.- Returns:
- A copy of the list of form fields for this form panel.
-
getFormField
Finds and returns a specific FormField by its identifier, if it exists. No validation of the FormField identifier is done in this class! If more than one FormField has the same identifier, this method will return whichever one it finds first. If a field does not have an identifier, it will not be considered by this method.- Parameters:
identifier- The field identifier to search for.- Returns:
- A FormField matching that identifier, or null if not found.
-
findFormField
Synonym for getFormField(String identifier).- Parameters:
identifier- The identifier to search for.- Returns:
- A FormField matching that identifier, or null if not found.
-
removeAllFormFields
Removes all FormFields from this FormPanel and re-renders it.- Returns:
- This FormPanel instance, to allow method chaining.
-
removeAll
public void removeAll()Overridden here so we can also remove all FormField instances. This is effectively the same as calling removeAllFormFields() and it will trigger a re-render. -
setEnabled
public void setEnabled(boolean enabled) Overridden here so we can enable/disable all FormField instances when we receive a setEnabled request.- Overrides:
setEnabledin classJComponent- Parameters:
enabled- true if this component should be enabled, false otherwise
-
add
Synonym for addAll(List<FormField> fields). -
addAll
Adds the specified list of FormFields to this FormPanel. -
add
Adds the specified FormField to this FormPanel. -
getFieldCount
public int getFieldCount()Returns the number of FormFields contained in this panel. -
clearValidationResults
Invoke this to clear the validation label off any previously validated field. Useful for when resetting a form to its initial state. -
isFormValid
public boolean isFormValid()Validates each FormField by invoking all FieldValidators that are attached to it, then returns the overall result. The return will be true if all FieldValidators for all FormFields validated successfully. -
validateForm
Shorthand for isFormValid() -
setAlignment
Changes the Alignment property of this FormPanel and re-renders it. -
getAlignment
Returns the Alignment property of this FormPanel. -
forceRerender
Deprecated, for removal: This API element is subject to removal in a future version.As of swing-extras 2.7. This method will be removed in a future release.This is an obsolete method from an earlier version of swing-forms. It is scheduled for removal in a future release. -
getMultiLineFieldExtraTopMargin
public int getMultiLineFieldExtraTopMargin()Returns the extra top margin, in pixels, that will be applied to multi-line field labels to better align them with their associated field components. -
setMultiLineFieldExtraTopMargin
There's a very slight misalignment issue with field labels on multi-line FormField implementations due to the way GridBagLayout anchors components. This property allows you to specify an extra top margin, in pixels, to be applied to multi-line field labels to better align them with their associated field components. The default value is 4 pixels, which is usually sufficient. You can set this to zero if you don't want any extra margin applied.- Parameters:
multiLineFieldExtraTopMargin- The extra top margin, in pixels, for multi-line field labels.- Returns:
- This FormPanel instance, to allow method chaining.
-