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.
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());
}
});
}
}
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
来源:https://stackoverflow.com/questions/6111003/its-possible-in-swing-configure-a-jtextfield-to-only-accept-numbers