带有 JFormattedTextField 的 KeyListener

KeyListener with JFormattedTextField

有人可以向我解释为什么 getValue() 函数 returns null 总是吗?如果我使用 getText() 而不是 getValue() 那么一切都是完美的,但我想要的是值而不是文本。我可以将它转换为整数,但我认为这不是最好的方法。

public class Test {    
    public static void main(String[] args) {

        JFrame jf = new JFrame("test jftf"); 
        jf.setSize(100, 100);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        jf.setVisible(true); 
        JFormattedTextField jftf = new JFormattedTextField(NumberFormat.getIntegerInstance()); 
        jftf.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
                System.out.println(jftf.getValue()); 
            }

        });
        jf.add(jftf); 
    }

}

如果您依赖 getValue() 方法,则需要确保当前编辑已提交。您可以通过调用方法 commitEdit() 来执行此操作,否则您可能无法获得预期的值:

@Override
public void keyReleased(KeyEvent e) {
    //Forces the current value to be taken from the AbstractFormatter 
    //and set as the current value:
    try {
        jftf.commitEdit();
    } catch (ParseException e1) {
        //Handle possible parsing error...
    }
    System.out.println(jftf.getValue()); 
}

这是一个说明其工作原理的示例,值的名称不准确。 可以这样想。 JFormattedTextField 有一个名为 lastValidInt 的字段,它包含一个整数。 每次格式化字段中的文本时,程序都会检查字段中的文本是否为数字。如果是,则 lastValidInt 将设置为该字符串。

getValue() 方法将检查 lastValidInt 是否已初始化,如果已初始化,则 returns lastValidInt[ 的值=23=]。如果还没有那么它 returns null.

例子: 这些假设您每次都重新启动应用程序。 输入是您将在该字段中写入的内容。 输出是输入内容后控制台打印的内容。

1:
Input: a
Ouput: null
//a is not a number therefore the output is null

2:
Input:  1
Output: 1
//1 is a number therefore the output is 1

3:
Input1: a
Ouput: null
Input2: as
Ouput: null
Input3: asd
Ouput: null
Input4: asdf
Ouput: null
//a is not a number therefore the output is null

4:
Input1: 1
Ouput: 1
Input2: 1f
Ouput: 1
//The first thing the was read here was 1 therefore lastValidInt was set to 1 then the next input is 1f which is not a number therefore lastValidInt remained 1

5:
Input1: f
Ouput: null
Input2: f1
Ouput: null
//f is not a number therefore output is null, f1 is not a number either since it has a character that is not a digit and therefore lastValidInt has not been initialized

6:
Input1: f
Ouput: null
Input2: 
Output: null
Input3: 1
Output: 1
Input4: 1f
Output: 1
//f is not a number therefore output is null, "" is also not a number therefore output is null again then the only thing that exists in the field is 1 which is a number therefore output is 1, finally by adding a f the field is no longer a number so output is same as before.

7:
Input1: f
Ouput: null
Input2: 1f (moved back to the begining without erasing f)
Output: null
//f is not a number therefore output is null, 1f is not a number either since it has a character that is not a digit and therefore lastValidInt has not been initialized