Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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];
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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading