JFormattedTextField for Double still takes characters(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 仍然需要字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Double 的 JFormattedTextField 仍然需要字符


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01