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

Community
  • 1
  • 1
Renato Dinhani
  • 35,057
  • 55
  • 139
  • 199
  • 4
    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/submit – Kaj May 24 '11 at 13:22
  • This has already been answered here: > http://stackoverflow.com/questions/1313390/is-there-any-way-to-accept-only-numeric-values-in-a-jtextfield – jjnguy May 24 '11 at 13:16

2 Answers2

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());
            }
        });
    }
}
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • -) strange searching rules there, errrghh I found that finally..., someone forgot for.. :-) http://forums.oracle.com/forums/thread.jspa?messageID=9337792 +1 – mKorbel May 24 '11 at 16:37
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

cdugga
  • 3,849
  • 17
  • 81
  • 127