David Tunnell
David Tunnell

Reputation: 7542

Apply .addKeyListener to array of JTextFields

I wrote the code below. It checks input from a JTextField and ensures the user is typing in numbers. If not the box flashes red and the invalid character is removed.

The tipArray[] is an array of JTextFields that I add to the JFrame with a loop.

How can I apply the following code to every possible array (tipArray[0], tipArray[1] ....tipArray[6])?

tipArray[6].addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
    char keyChar = e.getKeyChar();;
    char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!@#$%^&*()[,]{}<>_+=|\"':;?/ ".toCharArray();
        for (int i = 0; i < badCharArray.length; i++) {
            if (badCharArray[i] == keyChar) {
                tipArray[1].setBackground(Color.RED);
                }
                } 
            }
@Override
public void keyReleased(KeyEvent e) {
    if (tipArray[6].getBackground() == Color.RED) {
        if (tipArray[6].getText() != "0"){
            String removeLastLetter = tipArray[1].getText().substring(0, tipArray[6].getText().length()-1);
            tipArray[6].setText(removeLastLetter);
            tipArray[6].setBackground(Color.WHITE);
        }
    }
}

});

The loops I have tried dont work:

for (int i = 0; i <= 6; i++) {
tipArray[i].addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
    char keyChar = e.getKeyChar();;
    char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!@#$%^&*()[,]{}<>_+=|\"':;?/ ".toCharArray();
        for (int x = 0; x < badCharArray.length; x++) {
            if (badCharArray[x] == keyChar) {
                tipArray[i].setBackground(Color.RED);
                }
                } 
            }
@Override
public void keyReleased(KeyEvent e) {
    if (tipArray[i].getBackground() == Color.RED) {
        if (tipArray[i].getText() != "0"){
            String removeLastLetter = tipArray[i].getText().substring(0, tipArray[i].getText().length()-1);
            tipArray[i].setText(removeLastLetter);
            tipArray[i].setBackground(Color.WHITE);
        }
    }
}

});

}

^The above results in all of the variable i's after line "if (badCharArray[x] == keyChar) {" having a syntax error.

Upvotes: 1

Views: 445

Answers (1)

Alex Coleman
Alex Coleman

Reputation: 7326

Change your counter in the for loop in the second one to be a different variable (z instead of i perhaps). You have a duplicate variable the way it is now (two i's). Also, it is recommended you use a DocumentListener, not KeyListener, for checking for invalid characters, as KeyListeners sometimes fail.

Upvotes: 1

Related Questions