Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept only numbers and a dot in Java TextField

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();
                }
            }
        });
like image 361
Agustín Avatar asked Aug 06 '13 15:08

Agustín


People also ask

How do I make input only accept numbers in Java?

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) .

How do I allow only numbers in JTextField?

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.

How do I limit the number of characters in a textfield in Java?

We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.

How do you validate numbers in Java?

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.


2 Answers

I just use a try-catch block:

try {// if is number
    Integer.parseInt(String);
} catch (NumberFormatException e) {
    // else then do blah
}
like image 96
Brayan Byrdsong Avatar answered Oct 25 '22 08:10

Brayan Byrdsong


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);
like image 38
Suresh Atta Avatar answered Oct 25 '22 07:10

Suresh Atta