简体   繁体   中英

Arrow Keys, TextField focus in java?

I have a JPanel with 16 JTextfield (4x4) in it, I draw them using for loop.

Now, I want to use my arrow keys to move focus from this jtextfield to the other.

How can I do that?

Code (edit extracted from OP's answer)

private JTextField[] characters;

public void drawWords() {
pnlWords.removeAll();
pnlWords.setLayout(new GridLayout(4, 4));
characters = new JTextField[4 * 4];

for (int i = 0; i < 4 * 4; i++) {
    characters[i] = new JTextField();
    characters[i].setHorizontalAlignment(JLabel.CENTER);
    characters[i].setBackground(Color.LIGHT_GRAY);
    characters[i].setFont(font);
    characters[i].addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyTyped(java.awt.event.KeyEvent evt) {
            charactersKeyTyped(evt);
        }
    });
    pnlWords.add(characters[i]);
}
}


public void charactersKeyTyped(java.awt.event.KeyEvent evt) {
int key = evt.getKeyCode();        
    for (int i = 0; i < 4 * 4; i++) {
        switch (key) {
            case KeyEvent.VK_LEFT:
                characters[i - 1].requestFocus();
                break;
            case KeyEvent.VK_RIGHT:
                characters[i + 1].requestFocus();
                break;
            case KeyEvent.VK_UP:
                characters[i - 4].requestFocus();
                break;
            case KeyEvent.VK_DOWN:
                characters[i + 4].requestFocus();
                break;
        }
    }   
}

You could create an array of all of your JTextFields and a KeyAdapter to your panel. If the entered key is the right key, set the focus to the next JTextField in the array. If it's the left key, set the focus to the previous JTextField. Consider the difference between preincrement and postincrement in this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM