0

I am using the KeyEvent for the user to key in only numbers

private void txtvalue1KeyTyped(java.awt.event.KeyEvent evt) {                                 
    char c = evt.getKeyChar();
    if(!(Character.isDigit(c))|| c==KeyEvent.VK_BACK_SPACE ||  c==KeyEvent.VK_DELETE){
        evt.consume();
    }
}

My question is, is there a way to limit the max/min value in the text to # number. For example I want to limit the value of my textfield min of "1" and max value of "12".

Zero Serum
  • 39
  • 10
  • Don't use a KeyListener. For example your code won't work if text is pasted into the text field. Swing has newer and better API's as suggested below. – camickr Oct 09 '15 at 05:56
  • Possible duplicate of [How to implement in Java ( JTextField class ) to allow entering only digits?](http://stackoverflow.com/questions/5662651/how-to-implement-in-java-jtextfield-class-to-allow-entering-only-digits) – Optional Oct 09 '15 at 07:02

1 Answers1

3

Use a JSpinner. See the section from the Swing tutorial on How to Use Spinners for working examples.

A spinner will do the editing for numeric values and a valid range.

camickr
  • 321,443
  • 19
  • 166
  • 288