Move the Focus with the TAB Key in a JTextArea in Java

Description

The following code shows how to move the Focus with the TAB Key in a JTextArea.

Example


//from w  ww  .j a v a  2 s . c o m
import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextArea;

public class Main {
  public static void main(String[] argv) throws Exception {

    JTextArea component = new JTextArea();

    NextFocusAction nextFocusAction = new NextFocusAction();
    PrevFocusAction prevFocusAction = new PrevFocusAction();
    
    component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);
    component.getActionMap().put(prevFocusAction.getValue(Action.NAME), prevFocusAction);
  }
}

class NextFocusAction extends AbstractAction{
  public NextFocusAction(){
    super("Move Focus Forwards");
  }
  public void actionPerformed(ActionEvent evt) {
    ((Component) evt.getSource()).transferFocus();
  }
}
class PrevFocusAction extends AbstractAction {
  public PrevFocusAction(){
    super("Move Focus Backwards");
  }
  public void actionPerformed(ActionEvent evt) {
    ((Component) evt.getSource()).transferFocusBackward();
  }
}




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer