我有一个文本字段,我只接受来自键盘的数字,但现在我必须更改它,因为它是一个价格文本字段",我还需要接受一个点."适用于任何价格.
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 != '')) {
e.consume();
}
}
});
按照 Oracle 的建议,使用格式化文本字段
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 中只接受数字和点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!