0

I have the following JFormattedTextField

try {
    MaskFormatter CabinNoTextF = new MaskFormatter("###");
    CabinNoTextF.setPlaceholderCharacter(' ');
    CabinNoTextField = new JFormattedTextField(CabinNoTextF);
    centerPanelCabin.add(CabinNoTextField);
    addCabinF.add(centerPanelCabin);
    addCabinF.setVisible(true);
} catch (Exception ex) {
}

CabinNoTextField is formatted to only allow three digits to be inputted within the text field. However, I want it so that the user can also enter a single digit as well. I.e. the user may enter 1,15, or 100. But with the code above, the text field only allows three digits to be entered, if I enter a single digit within the text field, it automatically clears.

How do I allow CabinNoTextField to accept three digits at most, but the text field will accept a single digit and double digits as well.

user207421
  • 305,947
  • 44
  • 307
  • 483
Freddy
  • 683
  • 4
  • 35
  • 114
  • Consider using a `JSpinner` with a `SpinnerNumberModel` instead. – Andrew Thompson Feb 06 '15 at 23:16
  • 1
    Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is a `CONSTANT_ALL_UPPER`) and use it consistently. And don't ignore exceptions, it will come back to bite you in the buttocks. – Andrew Thompson Feb 06 '15 at 23:17

2 Answers2

3

Use a NumberFormat

NumberFormat amountFormat = NumberFormat.getNumberInstance();
amountFormat.setMinimumIntegerDigits(1);
amountFormat.setMaximumIntegerDigits(3);
amountFormat.setMaximumFractionDigits(0);

amountField = new JFormattedTextField(amountFormat);

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

2

Here's a simple example using InputVerifier:

JFormattedTextField f = new JFormattedTextField();
f.setInputVerifier(new InputVerifier() {
    @Override
    public boolean verify(JComponent input) {
        String text = ((JTextComponent) input).getText();
        return text.length() < 4 && StringUtil.isNumeric(text); // or use a regex
    }
});

Check this answer for more possibilities.

Community
  • 1
  • 1
alterfox
  • 1,675
  • 3
  • 22
  • 37