Search code examples
javaswingjtextfieldjformattedtextfield

Setting the maximum value that can be entered into a JFormattedTextField


I have the following code which only allows one numerical value to allowed in the field:

try {
  MaskFormatter deckLevelEntry = new MaskFormatter("#");
  deckLevelEntry.setPlaceholderCharacter('_');

  deckLevelEntryField = new JFormattedTextField(deckLevelEntry);
  detailsPanel.add(deckLevelEntryField);
  wholeFramePanel.add(detailsPanel);
  frame3.add(wholeFramePanel);
  frame3.setVisible(true);
  } catch (Exception ex) {
  }

However, is there a way, if so how, to set the maximum numerical value to be entered? by this I mean I want the following value's to be accepted in the JFormattedTextField: 1,2,3 and 4. Anything above 4 should not be allowed to entered. The same applies for the value of 0.


Solution

  • Use this:

    NumberFormatter nf = new NumberFormatter();
    nf.setMinimum(new Integer(30));
    nf.setMaximum(new Integer(70));
    final JFormattedTextField field = new JFormattedTextField(nf);