JFormattedTextField for Double仍然使用字符 [英] JFormattedTextField for Double still takes characters

查看:87
本文介绍了JFormattedTextField for Double仍然使用字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JFormattedTextField,用户输入价格,我有这个,但如果我输入一个字符,它会让我反正。我需要这个文本字段才能读取数字,或者从键盘读取数据,如果它是一个字符,则忽略它。我应该如何更改它以使其工作?

I have a JFormattedTextField where the user would input prices, I have this, but if I type a character, it'll let me anyway. I need this text field to only read numbers or , from the keyboard, and ignore if it's a char. How should I change it in order to make it work?

JFormattedTextField formattedTextField = new JFormattedTextField();
        formattedTextField.setBounds(25, 330, 56, 20);
        contentPanel.add(formattedTextField);
        formattedTextField.setValue(new Double(10.0));


推荐答案

您需要设置一个格式化器:

You need to set a Formatter:

NumberFormat f = NumberFormat.getNumberInstance(); 
JFormattedTextField field = new JFormattedTextField(f);

看看:
格式



NumberFormat

然后尝试这样:

PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
    @Override
    public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) 
        throws BadLocationException 
    {
        fb.insertString(off, str.replaceAll("\\D++", ""), attr);  // remove non-digits
    } 
    @Override
    public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) 
        throws BadLocationException 
    {
        fb.replace(off, len, str.replaceAll("\\D++", ""), attr);  // remove non-digits
    }
});

JFormattedTextField field = new JFormattedTextField();
field.setDocument(doc);

这篇关于JFormattedTextField for Double仍然使用字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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