It's possible in Swing configure a JTextField to only accept numbers? [duplicate]
Asked Answered
F

2

-1

Possible Duplicate:
Is there any way to accept only numeric values in a JTextField?

There any functionality on the JTextField of Swing that allow only positive numbers inside a range of numbers?

Example: I can only enter numbers between 10 and 30. Numbers out of this range will not even appear in the field.

Frey answered 24/5, 2011 at 13:14 Comment(2)
This has already been answered here: > #1313890Trapan
How will you be able to enter 17 if it doesn't accept "1" as input? It's better to validate the input on save/submitKunlun
F
12

Use a JSpinner with a SpinnerNumberModel - the end user will thank you. OK not literally, but at least they will not curse your name for forcing them to type in something they'd like to choose using the arrow keys.

E.G.

import javax.swing.*;

class NumberChooser {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SpinnerNumberModel numberModel = new SpinnerNumberModel(
                    new Integer(15), // value
                    new Integer(10), // min
                    new Integer(30), // max
                    new Integer(1) // step
                    );
                JSpinner numberChooser = new JSpinner(numberModel);
                JOptionPane.showMessageDialog(null, numberChooser);
                System.out.println("Number: " + numberChooser.getValue());
            }
        });
    }
}
Foltz answered 24/5, 2011 at 13:22 Comment(1)
-) strange searching rules there, errrghh I found that finally..., someone forgot for.. :-) forums.oracle.com/forums/… +1Braces
W
0

create a custom classes extending PlainDocument

public class NumericDocument extends PlainDocument

In this class override the insertString. Plenty of examples online which use the Character.isDigit method to check each inputted value to check if numeric or not.

The when your creating you JTextField do so using the

JTextField numericTextOnlyField = new JTextField(new NumericDocument())

inside the insertString method you can check to see of the values inserted are within the range you allow

Wismar answered 24/5, 2011 at 13:26 Comment(2)
That won't restrict the input to values between 10 and 30.Kunlun
Better to use a DocumentFilter as has been described many times here.Pacificas

© 2022 - 2024 — McMap. All rights reserved.