Home > database >  How can I move my caret on the other JTextField
How can I move my caret on the other JTextField

Time:04-17

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];
CaretMove(){
    setSize(300, 150);
    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
    setLocationRelativeTo(null);
    Border border = BorderFactory.createLineBorder(null, 6);
    for (int i=0;i<3;i  ) {
        jTextField[i] = new JTextField(10);
        jTextField[i].addKeyListener(this);
        jTextField[i].setBorder(border);
        add(jTextField[i]);
    }
    pack();
    setVisible(true);
}

@Override
public void keyTyped(KeyEvent e) {
}

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

@Override
public void keyReleased(KeyEvent e) {

}

Image

CodePudding user response:

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.

  • Related