Class JKeyStrokeField
- java.lang.Object
-
- java.awt.Component
-
- java.awt.Container
-
- javax.swing.JComponent
-
- javax.swing.text.JTextComponent
-
- javax.swing.JTextField
-
- ca.cgjennings.ui.JKeyStrokeField
-
- All Implemented Interfaces:
java.awt.image.ImageObserver,java.awt.MenuContainer,java.io.Serializable,javax.accessibility.Accessible,javax.swing.Scrollable,javax.swing.SwingConstants
public class JKeyStrokeField extends javax.swing.JTextFieldA field that allows the user to choose a key stroke by pressing the desired key combination. A typical application is allowing the user to define accelerator keys for commands.By default, the field limits acceptable keys to those that make sense as accelerators: function keys, or other keys with at least one modifier (Ctrl, Alt, AltGr, or Meta). This filtering can be disabled. Subclasses may also implement their own policy for accepting or rejecting key strokes by overriding
filterKeyStroke(javax.swing.KeyStroke).Rejected key strokes are displayed to the user for as long as the key stroke is held down using the colours defined for selected text. (By default, this will display the rejected stroke in red.) When the rejected key stroke is released, the text will return to the last valid key stroke.
The
nullvalue is valid if there is no key stroke, as when editing the key for a command with no accelerator assigned. This is displayed as an empty field. By default, the Delete and Back Space keys will all set the current key stroke tonullif they are pressed unmodified.- Author:
- Chris Jennings
- See Also:
- Serialized Form
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class javax.swing.JTextField
javax.swing.JTextField.AccessibleJTextField
-
Nested classes/interfaces inherited from class javax.swing.text.JTextComponent
javax.swing.text.JTextComponent.AccessibleJTextComponent, javax.swing.text.JTextComponent.DropLocation, javax.swing.text.JTextComponent.KeyBinding
-
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.StringPROPERTY_KEY_STROKE_CHANGEThe name of a vetoable property that is fired when the the key stroke is about to change.-
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_WINDOW
-
Fields inherited from class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
-
-
Constructor Summary
Constructors Constructor Description JKeyStrokeField()Creates a new key stroke field that filters out "normal" keys that wouldn't be used for a command accelerator (seefilterKeyStroke(javax.swing.KeyStroke)).JKeyStrokeField(boolean filterPlainKeyStrokes)Creates a new key stroke field.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description protected javax.swing.KeyStrokefilterKeyStroke(javax.swing.KeyStroke ks)Accepts, rejects, or transforms key strokes.static javax.swing.KeyStrokefromDisplayString(java.lang.String s)Returns a key stroke for a string that uses the same syntax as the text display in a KeyStrokeField.javax.swing.KeyStrokegetKeyStroke()Gets the current key stroke.protected booleanisClearKey(javax.swing.KeyStroke ks)Returnstrueif the key stroke should be interpreted as a request to clear the field.booleanisDefaultClearKeyEnabled()Iftrue, then the Delete and Back Space keys (without modifiers) will all be interpreted as a request to set the key stroke tonull, clearing the field.booleanisKeyStrokeValid(javax.swing.KeyStroke ks)Returnstrueif the key stroke will be accepted by the filtering policy.voidsetDefaultClearKeyEnabled(boolean enable)Enables or disables the clear key mechanism.voidsetKeyStroke(javax.swing.KeyStroke ks)Sets the current key stroke to ks.static java.lang.StringtoDisplayString(javax.swing.KeyStroke ks)Converts a key stroke into a string with the same format used to display key strokes by a KeyStrokeField.-
Methods inherited from class javax.swing.JTextField
actionPropertyChanged, addActionListener, configurePropertiesFromAction, createActionPropertyChangeListener, createDefaultModel, fireActionPerformed, getAccessibleContext, getAction, getActionListeners, getActions, getColumns, getColumnWidth, getHorizontalAlignment, getHorizontalVisibility, getPreferredSize, getScrollOffset, getUIClassID, isValidateRoot, paramString, postActionEvent, removeActionListener, scrollRectToVisible, setAction, setActionCommand, setColumns, setDocument, setFont, setHorizontalAlignment, setScrollOffset
-
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, modelToView2D, moveCaretPosition, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateUI, viewToModel, viewToModel2D, write
-
Methods 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, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
-
Methods 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, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
-
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, 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, 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, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
-
-
-
Field Detail
-
PROPERTY_KEY_STROKE_CHANGE
public static final java.lang.String PROPERTY_KEY_STROKE_CHANGE
The name of a vetoable property that is fired when the the key stroke is about to change. This allows listeners to listen for selection changes or filter out unacceptable keys (by vetoing the change). For example, a tool that configures command keys might veto keys that are already in use.- See Also:
- Constant Field Values
-
-
Constructor Detail
-
JKeyStrokeField
public JKeyStrokeField()
Creates a new key stroke field that filters out "normal" keys that wouldn't be used for a command accelerator (seefilterKeyStroke(javax.swing.KeyStroke)).
-
JKeyStrokeField
public JKeyStrokeField(boolean filterPlainKeyStrokes)
Creates a new key stroke field. If filterPlainKeyStrokes is true, then keys that are not sensible as command accelerator keys will be rejected.- Parameters:
filterPlainKeyStrokes-
-
-
Method Detail
-
setKeyStroke
public void setKeyStroke(javax.swing.KeyStroke ks)
Sets the current key stroke to ks. Note that this may be used to set the keystroke to a value that would otherwise be invalid. The valuenullmay be used to indicate that no key stroke is set, and will be displayed to the user as an empty string.- Parameters:
ks- the key stroke to make current
-
getKeyStroke
public javax.swing.KeyStroke getKeyStroke()
Gets the current key stroke. This is the most recent of: the key stoke set bysetKeyStroke(javax.swing.KeyStroke), or the last key stroke typed by the user and accepted byfilterKeyStroke(javax.swing.KeyStroke). This value can benull, meaning that no key stroke has been set.
-
isKeyStrokeValid
public boolean isKeyStrokeValid(javax.swing.KeyStroke ks)
Returnstrueif the key stroke will be accepted by the filtering policy.- Returns:
trueif filtering is disabled or the key stroke is accepted
-
isDefaultClearKeyEnabled
public boolean isDefaultClearKeyEnabled()
Iftrue, then the Delete and Back Space keys (without modifiers) will all be interpreted as a request to set the key stroke tonull, clearing the field.- Returns:
trueif clear keys are enabled
-
setDefaultClearKeyEnabled
public void setDefaultClearKeyEnabled(boolean enable)
Enables or disables the clear key mechanism. This interprets Delete or Back Space as an attempt to clear the field. When pressed (unmodified), the key stroke will be set tonull.- Parameters:
enable- if the default key clearing mechanism should be applied
-
isClearKey
protected boolean isClearKey(javax.swing.KeyStroke ks)
Returnstrueif the key stroke should be interpreted as a request to clear the field. Subclasses may override this to change the keys used by the default key clearing mechanism.- Parameters:
ks- the key stroke that may be a clear key- Returns:
trueif the key should clear the field
-
filterKeyStroke
protected javax.swing.KeyStroke filterKeyStroke(javax.swing.KeyStroke ks)
Accepts, rejects, or transforms key strokes. This method is called when a key stroke has been completed. It may either return the key stroke (to accept it), substitute a different key stroke, or returnnullto reject the key stroke. Subclasses may override this to customize the set of keys that are accepted. The default behaviour is to reject key strokes if they consist only of modifiers or if they do not include at least one modifier other than Shift (except for the function keys, which are always accepted).- Parameters:
ks- the key stroke to filter- Returns:
nullto reject the key stroke, otherwise the (possibly replaced) key stroke
-
fromDisplayString
public static javax.swing.KeyStroke fromDisplayString(java.lang.String s)
Returns a key stroke for a string that uses the same syntax as the text display in a KeyStrokeField.- Parameters:
s- the string to parse- Returns:
- the key stroke that matches the string, or
nullif the string could not be parsed
-
toDisplayString
public static java.lang.String toDisplayString(javax.swing.KeyStroke ks)
Converts a key stroke into a string with the same format used to display key strokes by a KeyStrokeField. This consists of a series of zero or more modifier key names with trailing plus symbols, followed by a key name for the non-modifier key (if any) as given byKeyEvent.getKeyText(). For example: Ctrl+Shift+ (only the control and shift modifiers are held), or Ctrl+Alt+X (two modifiers and the non-modifier X are held). A null key stroke is converted to the empty string.- Parameters:
ks- the key to convert- Returns:
- a string representation for the key stroke
-
-