Transfer cursor from one JTextField to another on Enter press?

user2286075 picture user2286075 · May 10, 2013 · Viewed 7.1k times · Source

I have one JTextField called Name and one JTextArea called Address. My requirement is when user has entered name in the JTextFieldand pressed Enter key the cursor should go to the next text area which is Address.

Currently one can move from one textfield to other by pressing the tab key (which I believe is default). I would like to prohibit this and transfer the cursor only via the ENTER key.

I have tried transferfocus(), but enter key does not take the cursor to the text area. How do I achieve this?

Answer

camickr picture camickr · May 10, 2013

My requirement is when user has entered name in the JTextFieldand pressed enter key the cursor should go to the next text area which is Address.

Assuming the components follow one another in the normal tabbing order you can write general code:

Action enterAction = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.getFocusOwner().transferFocus();
    }
}

...

textField.addActionListener( enterAction );

Currently one can move from one textfield to other by pressing the tab key (which I believe is default). I would like to prohibit this and transfer the cursor only via the ENTER key.

Why do you want to prohibit this. As you say tab is the default so most user will be familiar with this approach. Don't reinvent a UI and give the users a choice.