【问题标题】:How to restrict textfield input only number and decimal? [duplicate]如何限制文本字段仅输入数字和小数? [复制]
【发布时间】:2019-12-08 18:43:06
【问题描述】:

我想控制 jtextfield 上的用户输入文本。看来我在 netbean 8 中找不到任何好方法。在 C# 中使用 keypress event,但在 java 中我是新手。

我选择key type事件

我只想输入小数点后2位的数字

10.00
1224547885544.12
545545464646464646465466.10

不是

12121212.654654654654

我试过了

                 // not a good idea

       char c=evt.getKeyChar();
    if((Character.isDigit(c))||(c==KeyEvent.VK_PERIOD)||(c==KeyEvent.VK_BACK_SPACE)){
        int punto=0;
        if(c==KeyEvent.VK_PERIOD){ 
                    String s=pricefield.getText();
                    int dot=s.indexOf('.');
                    punto=dot;
                    if(dot!=-1){
                        getToolkit().beep();
                        evt.consume();
                    }
                }
    }
    else{    
        getToolkit().beep();
        evt.consume();
    }

    //second try

   char enter = evt.getKeyChar();
if(!(Character.isDigit(enter))){
    evt.consume();
}

我认为这不是个好主意。

尝试其他多种方式。

请帮帮我。

【问题讨论】:

    标签: java


    【解决方案1】:

    假设您指的是 JavaFX TextField

    您可以通过调用textField.textProperty() 获取文本字段的textProperty。由于这是一个属性,您可以为其附加一个侦听器,以侦听字段中文本的更改:

    textField.textProperty().addListener((observable, oldValue, newValue) -> {
        // this code is called whenever the text in the field changes
        // oldValue is the text contained before the event was triggered
        // newValue is the text that the field is about to be set to
    
        if (oldValue.contains("[a-zA-Z]")) {  // any predicate you want/need
            textField.setText(oldValue);  // revert the text of the field back to its old value
        }
    });
    

    【讨论】:

    • 我想控制用户从键盘直接输入到文本字段的时间。用户只能输入数字而不是字母或符号,而是“。”被允许。小数点后用户只能输入 2 位数字。格式如(1111111.11)
    • 您将不得不稍微修改if 语句,但是通过“正则表达式”的快速谷歌搜索,从这段代码中应该很简单
    【解决方案2】:

    对于 Swing TextField,这应该对您有所帮助:

     JFormattedTextField textField = new JFormattedTextField();
            textField.setFormatterFactory(new AbstractFormatterFactory() {
                @Override
                public AbstractFormatter getFormatter(JFormattedTextField tf) {
                    NumberFormat format = DecimalFormat.getInstance();
                    //or two, if you want to force something like 10.00
                    format.setMinimumFractionDigits(0); 
                    format.setMaximumFractionDigits(2);
                    format.setRoundingMode(RoundingMode.HALF_UP);
                    InternationalFormatter formatter = new InternationalFormatter(format);
                    formatter.setAllowsInvalid(false); //important!
                    return formatter;
                }
            });
    

    【讨论】:

    • 这种情况下在java中的keytype事件或C#中的按键,控制用户从键盘输入到文本字段
    • 哦,我没听明白,那你需要像cameron显示的那样绑定一个监听器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2020-01-11
    相关资源
    最近更新 更多