Class 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.JTextField
    A 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 null value 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 to null if 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
      • Nested classes/interfaces inherited from class java.awt.Container

        java.awt.Container.AccessibleAWTContainer
      • Nested classes/interfaces inherited from class java.awt.Component

        java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static 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.
      • Fields inherited from class javax.swing.JTextField

        notifyAction
      • Fields inherited from class javax.swing.text.JTextComponent

        DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
      • 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
      • Fields inherited from interface java.awt.image.ImageObserver

        ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
      • Fields 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
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected javax.swing.KeyStroke filterKeyStroke​(javax.swing.KeyStroke ks)
      Accepts, rejects, or transforms key strokes.
      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.
      javax.swing.KeyStroke getKeyStroke()
      Gets the current key stroke.
      protected boolean isClearKey​(javax.swing.KeyStroke ks)
      Returns true if the key stroke should be interpreted as a request to clear the field.
      boolean isDefaultClearKeyEnabled()
      If true, then the Delete and Back Space keys (without modifiers) will all be interpreted as a request to set the key stroke to null, clearing the field.
      boolean isKeyStrokeValid​(javax.swing.KeyStroke ks)
      Returns true if the key stroke will be accepted by the filtering policy.
      void setDefaultClearKeyEnabled​(boolean enable)
      Enables or disables the clear key mechanism.
      void setKeyStroke​(javax.swing.KeyStroke ks)
      Sets the current key stroke to ks.
      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.
      • 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
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • 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 (see filterKeyStroke(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 value null may 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
      • isKeyStrokeValid

        public boolean isKeyStrokeValid​(javax.swing.KeyStroke ks)
        Returns true if the key stroke will be accepted by the filtering policy.
        Returns:
        true if filtering is disabled or the key stroke is accepted
      • isDefaultClearKeyEnabled

        public boolean isDefaultClearKeyEnabled()
        If true, then the Delete and Back Space keys (without modifiers) will all be interpreted as a request to set the key stroke to null, clearing the field.
        Returns:
        true if 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 to null.
        Parameters:
        enable - if the default key clearing mechanism should be applied
      • isClearKey

        protected boolean isClearKey​(javax.swing.KeyStroke ks)
        Returns true if 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:
        true if 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 return null to 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:
        null to 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 null if 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 by KeyEvent.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