JFormattedTextField is not accepting any characters

0

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

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

JFormattedTextField txtQuantia = new JFormattedTextField(mskQuantia);

Remembering that I did not need to put a try / catch to instantiate the mask ...

    
asked by anonymous 22.06.2016 / 20:32

2 answers

1

As you are doing, no mask is being applied to the field. You are only initiating the variable mskQuantia , but without any valid mask.

The method setValidCharacters() only filters what you want to be accepted in the mask applied in the field, hence we return to the previous paragraph, you are not applying any mask, even though you are "installing" MaskFormatter empty in the field. >

This answer about how to do this restriction in JTextField may be the most recommended option for the case you want , since there is less compromise with mask or formatting than must be typed.

Just adapt the code by removing the maximum quantity limitation of characters:

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());
    
22.06.2016 / 20:49
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 does not even have to be a formatted field.

    
23.06.2016 / 06:08