在 Java TextField 中只接受数字和一个点 [英] Accept only numbers and a dot in Java TextField

查看:26
本文介绍了在 Java TextField 中只接受数字和一个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 textField,我只接受来自键盘的数字,但现在我必须更改它,因为它是一个price textField",我还需要接受一个点."任何价格.

I've got one textField where I only accept numbers from the keyboard, but now I have to change it as it's a "price textField" and I would also need to accept a dot "." for any kind of prices.

我怎样才能改变它以获得我需要的东西?

How can I change this in order to get what I need?

ptoMinimoField = new JTextField();
        ptoMinimoField.setBounds(348, 177, 167, 20);
        contentPanel.add(ptoMinimoField);
        ptoMinimoField.setColumns(10);
        ptoMinimoField.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                char caracter = e.getKeyChar();
                if (((caracter < '0') || (caracter > '9'))
                        && (caracter != '')) {
                    e.consume();
                }
            }
        });

推荐答案

如 Oracle 所建议的,使用格式化文本字段

As suggested by Oracle ,Use Formatted Text Fields

格式化文本字段为开发人员提供了一种指定可在文本字段中键入的有效字符集的方法.

Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field.

amountFormat = NumberFormat.getNumberInstance();
...
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);

这篇关于在 Java TextField 中只接受数字和一个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆