只接受Java TextField中的数字和点 [英] Accept only numbers and a dot in Java TextField
本文介绍了只接受Java TextField中的数字和点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个textField,我只接受键盘上的数字,但现在我不得不改变它,因为它是价格textField,我也需要接受一个点。任何形式的价格。
我怎样才能得到我需要的?
ptoMinimoField = new JTextField();
ptoMinimoField.setBounds(348,177,167,20);
contentPanel.add(ptoMinimoField);
ptoMinimoField.setColumns(10);
ptoMinimoField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
char caracter = e.getKeyChar();
if(((caracter< 0))||(caracter>'9'))
&&(caracter!='\b')){
e.consume();
}
}
});
解决方案
正如Oracle建议的那样,使用带格式的文本字段
带格式的文本字段为开发人员提供了一种指定可在文本字段中键入的有效字符集的方法。
amountFormat = NumberFormat.getNumberInstance();
...
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener(value,this);
I've got one textField where I only accept numbers from the keyboard, but now I have to change it as it's a "price textField" and I would also need to accept a dot "." for any kind of prices.
How can I change this in order to get what I need?
ptoMinimoField = new JTextField();
ptoMinimoField.setBounds(348, 177, 167, 20);
contentPanel.add(ptoMinimoField);
ptoMinimoField.setColumns(10);
ptoMinimoField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9'))
&& (caracter != '\b')) {
e.consume();
}
}
});
解决方案
As suggested by Oracle ,Use Formatted Text Fields
Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field.
amountFormat = NumberFormat.getNumberInstance();
...
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);
这篇关于只接受Java TextField中的数字和点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文