我有一个 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 仍然需要字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!