Jformattedtextfield is accepting no characters

Asked

Viewed 130 times

0

I have a window where we have a JFomattedTextField called txtQuantia, I applied a mask to him called mskQuantia, and set the valid characters, in this case, 0-9, but this field is not accepting any characters ... What can be ?

MaskFormatter mskQuantia = new MaskFormatter();
mskQuantia.setValidCharacters("0123456789");

JFormattedTextField txtQuantia = new JFormattedTextField(mskQuantia);

Remembering that I didn’t have to put one try/catch to instantiate the mask ...

  • Why didn’t you apply any mask.

  • It’s because in fact, I don’t want to apply mask to limit the digits (for example ###), I just want the field to accept numbers, no limits ...

2 answers

1


As you are doing, no masks are being applied in the field. You are just starting the variable mskQuantia, but without any valid mask.

The method setValidCharacters() just filter what you want to be accepted in the mask applied in the field, then we return to the previous paragraph, you are not applying any mask, despite being "installing" the MaskFormatter empty in the field.

This answer on how to do this restriction in Jtextfield may be the most recommended option for the case you want, since there is not so much commitment to mask or formatting what should be typed.

Simply adapt the code by removing the maximum number of characters limitation:

import javax.swing.text.PlainDocument;

class JTextFieldFilter extends PlainDocument {

    JTextFieldLimit() {
        super();
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }
        super.insertString(offset, str.replaceAll("\\D++", ""), attr);
    }
}

The above Code should be applied to JTextField as follows:

seuJTextField.setDocument(new JTextFieldFilter());

0

You can add a keytyped event.

  private void campoSomenteNumero(java.awt.event.KeyEvent evt) {
   String num = "0123456789";
        if (!num.contains(evt.getKeyChar() + "") {
            evt.consume();
        }
     }

Something like this doesn’t even need to be formatted field.

  • To filter in text fields, it is not recommended to use keystrokes like this, besides being more expensive for application, will not filter something pasted through a control + V. Recommended and correct is to use plainDocument or even Documentfilter.

  • You can override 'control' + 'V', I remember doing this last year using the same event capture method.

  • Then you will be adding unnecessary restriction to the field, only with plaindocument. this filtering is already done, regardless if the content was typed or pasted. Complicating something that can be simple is silly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.