jTextField验证数字和一个小数点? [英] jTextField validation for numbers and one decimal point?

查看:120
本文介绍了jTextField验证数字和一个小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将jTextField设置为仅接受数字和一个小数点.小数点不能输入超过一次,并且不允许其他字符.我该怎么办?

I need to set a jTextField to accept only numbers and one decimal point.Nothing else. Decimal point can't be typed more than once and no other characters are allowed. How can I do this?

我输入了此代码.但效果不佳.我的意思是直到我键入小数点为止

I typed this code. but it doesn't work well. I mean it accept Strings until i type a decimal point

    if (!Character.isDigit(evt.getKeyChar()) & crqty.getText().indexOf(".") != -1) {
        evt.consume();
    }

推荐答案

您似乎正在使用KeyListener来管理KeyEvents in the JTextField.这不适合过滤此JTextComponent的文档.在这里,您可以结合使用JFormattedTextFieldMaskFormatter来接受最多8位数字,并用小数点分隔.

You appear to be using a KeyListener to manage KeyEvents in theJTextField. This is not a suitable for filtering the document of this JTextComponent. Here you could use a JFormattedTextField combined with a MaskFormatter to accept a maximum 8 digits separated by a decimal point.

JFormattedTextField textField = new JFormattedTextField();
MaskFormatter dateMask = new MaskFormatter("####.####");
dateMask.install(textField);

对于更自由格式的输入(例如,更多数字),可以将DocumentFilterJTextField结合使用.这是一个整数过滤器示例

For a more free-format input (e.g. more digits) you could use a DocumentFilter with a JTextField. Here is an integer filter example

这篇关于jTextField验证数字和一个小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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