如何刷新 JTextField 的值以匹配实际值?

How to refresh JTextField's value to match real value?

我正在填写此表格,要求填写姓名、姓氏、性别、身高等... 我添加了 keyTyped 操作处理程序来进行完整性检查,(仅命名字母、年龄最大 2 数字等)

事实是,跳棋有效,但我在表格中看到的值与实际值不匹配,例如我为身高写了“1.333”(以米为单位),跳棋就完成了它的工作并告诉用户只接受像 1.33 这样的值。

所以我用了

formattedTextField.setText(StringUtils.substring(formattedTextField.getText(), 0, 4));

如果我在 TextField 中写入 1.333,实际存储的值是 1.33,但 1.333 保留在 TextField 中

这是我试过的

    formattedTextField = new JFormattedTextField();
    formattedTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent arg0) {
            String re1="^([+-]?\d*\.?\d*)$";
            System.out.println(formattedTextField.getText().matches(re1));
            if(formattedTextField.getText().length() >= 1 &&  formattedTextField.getText().matches(re1) == true)
            {                       

                if(formattedTextField.getText().length() >= 3)
                {
                    final BalloonTip balloonTip = new BalloonTip(
                            formattedTextField,
                            new JLabel("<html>Solo se aceptan valores de altura, como 1.66, 1.76, 1.88, etc..</html>"),
                            style,
                            BalloonTip.Orientation.LEFT_ABOVE,
                            BalloonTip.AttachLocation.ALIGNED,
                            20, 10,
                            false
                        );
                    TimingUtils.showTimedBalloon(balloonTip, 4500);
                    formattedTextField.setText(StringUtils.substring(formattedTextField.getText(), 0, 4));



                }
            }

        }
    });
contentPane.add(formattedTextField, "cell 2 9,growx,aligny center");

试试这个: 创建 3 个全局变量:

private String oldValue;
private final Pattern pattern = Pattern.compile("^\d+\.?\d{0,2}$");
private Matcher matcher;

你需要存储旧值并用正则表达式比较新值

formattedTextField.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent evt) {
            oldValue = formattedTextField.getText();
    }

    public void keyReleased(KeyEvent evt) {
        matcher = pattern.matcher(formattedTextField.getText());
        if(!matcher.matches()){
            formattedTextField.setText(oldValue);
        }
    }
}