将.addKeyListener应用于JTextFields数组

时间:2012-08-07 00:16:12

标签: java swing event-handling jtextfield

我写了下面的代码。它检查来自JTextField的输入并确保用户输入数字。如果不是,则框闪烁红色并且删除无效字符。

tipArray []是一个JTextFields数组,我通过循环添加到JFrame中。

如何将以下代码应用于每个可能的数组(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);
        }
    }
}

});

我尝试过的循环不起作用:

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);
        }
    }
}

});

}

^以上结果导致所有变量i在行之后“if(badCharArray [x] == keyChar){”有语法错误。

1 个答案:

答案 0 :(得分:1)

将第二个中的for循环中的计数器更改为另一个变量(z而不是i)。你有一个重复的变量,它现在的方式(两个我)。此外,建议您使用DocumentListener而不是KeyListener来检查无效字符,因为KeyListener有时会失败。