Search code examples
javaswingjtextfield

Is there a way to limit the numeric value of JTextField


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


Solution

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