Search code examples
javaswingvalidationjformattedtextfield

How to use JFormattedTextField allowing only letters and numbers


I have this code and cannot get MaskFormatter right
maskformatter

MaskFormatter formatter = null;
  try {
    formatter = new MaskFormatter("HHHHHHH");
  } catch (ParseException e) {
    e.printStackTrace();
  }

txtTroll = new JFormattedTextField(formatter);

I need Any hex character (0-9, a-z or A-Z) and the "H" should
give me only (0-9, a-z or A-Z) but im getting it wrong.

When i type text only capital letters are typed and it's slow to
and when i click away from the txtTroll all letters vanish


Solution

  • u can use another solution that i prefer

    write ur Document class and rewrite it's insertString method using regex expr

    example:

    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.PlainDocument;
    
    /**
    *
    * @author cpp-qt
    */
    public class HexDocument extends PlainDocument {
    
    private String text = "";
    
    @Override
    public void insertString(int offset, String txt, AttributeSet a) {
        try {
            text = getText(0, getLength());
            if ((text + txt).matches("[0-9a-fA-F]{0,7}")) {
                super.insertString(offset, txt, a);
            }
         } catch (Exception ex) {
            Logger.getLogger(HexDocument.class.getName()).log(Level.SEVERE, null, ex);
         }
    
        }
    }
    

    then

    set it as ur textField's document like this this.jTextField1.setDocument(new HexDocument());

    i think this is better than using jFormattedTextField