1

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

tipArray[] 是一个 JTextField 数组,我通过循环将其添加到 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);
        }
    }
}

});

}

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

4

1 回答 1

1

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

于 2012-08-07T00:17:56.917 回答