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();
}
}
});
To only accept numbers, you can do something similar using the Character. isDigit(char) function, but note that you will have to read the input as a String not a double , or get the input as a double and the converting it to String using Double. toString(d) .
By default, a JTextField can allow numbers, characters, and special characters. Validating user input that is typed into a JTextField can be difficult, especially if the input string must be converted to a numeric value such as an int. In the below example, JTextField only allows entering numeric values.
We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.
Mobile number validation in Java is done using Pattern and Matcher classes of Java. The pattern class is used to compile the given pattern/regular expression and the matcher class is used to match the input string with compiled pattern/regular expression.
I just use a try
-catch
block:
try {// if is number
Integer.parseInt(String);
} catch (NumberFormatException e) {
// else then do blah
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With