Double 的 JFormattedTextField 仍然需要字符 [英] JFormattedTextField for Double still takes characters

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

问题描述

我有一个 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));

推荐答案

需要设置一个Formatter:

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);

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

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