The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JTextArea  [7 examples]

e986. Moving the Focus with the TAB Key in a JTextArea Component

By default, typing TAB in a JTextArea inserts a TAB character. This example demonstrates how to modify the behavior so that typing TAB moves the focus to the next focusable component.

Rather than try to find the inputmap or keymap with the TAB binding and remove it, it is better to add an overriding key binding that will move the focus. The reason is that the location of the default TAB binding might change in some future version.

    JTextArea component = new JTextArea();
    
    // Add actions
    component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);
    component.getActionMap().put(prevFocusAction.getValue(Action.NAME), prevFocusAction);
    
    // The actions
    public Action nextFocusAction = new AbstractAction("Move Focus Forwards") {
        public void actionPerformed(ActionEvent evt) {
            ((Component)evt.getSource()).transferFocus();
        }
    };
    public Action prevFocusAction = new AbstractAction("Move Focus Backwards") {
        public void actionPerformed(ActionEvent evt) {
            ((Component)evt.getSource()).transferFocusBackward();
        }
    };

 Related Examples
e982. Creating a JTextArea Component
e983. Modifying Text in a JTextArea Component
e984. Enumerating the Lines in a JTextArea Component
e985. Setting the Tab Size of a JTextArea Component
e987. Enabling Word-Wrapping and Line-Wrapping in a JTextArea Component
e988. Implementing a Console Window with a JTextArea Component

See also: Actions and Key Bindings    Caret and Selection    Events    JEditorPane    JFormattedTextField    JTextComponent    JTextField    JTextPane    Styles   


© 2002 Addison-Wesley.