How can I move my caret on the other JTextField

I have this code that create some text fields and I want that my caret changes his position to the other JTextField after pressing ENTER. Is it possible to do this? In the picture, I gave an example of how caret transfer should work.

class CaretMove extends JFrame implements KeyListener {
JTextField jTextField[] = new JTextField[3];
    setSize(300, 150);
    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
    Border border = BorderFactory.createLineBorder(null, 6);
    for (int i=0;i<3;i++) {
        jTextField[i] = new JTextField(10);

public void keyTyped(KeyEvent e) {

public void keyPressed(KeyEvent e) {
    if (e.getKeyChar() == KeyEvent.VK_ENTER){
        JTextField jTextFiel = (JTextField)e.getSource();
        if ( jTextFiel == jTextField[2])
        else {
            e.setSource(jTextField[Arrays.asList(jTextField).indexOf(jTextFiel) + 1]);
            ((JTextField) e.getSource()).setText("meow"); //test meow
            ((JTextField) e.getSource()).setCaret(new MyCaret());

public void keyReleased(KeyEvent e) {



>Solution :

First and foremost, never add a KeyListener to a Swing text component as this can have bad side effects on the text component’s innate functionality.

Instead, if you want to capture an enter keypress, simply add an ActionListener to the JTextField as this will be triggered by the enter keypress. You can then call .requestFocusInWindow() on the other JTextField from within this listener, and this will transfer the keyboard focus to the new JTextField.

Leave a Reply