简体   繁体   中英

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, az or AZ) and the "H" should
give me only (0-9, az or AZ) 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

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

There are some problems in your assumption, make sure what you need, if you need letters and numbers, HEX is not what you need,

"H" should give me only (0-9, az or AZ) but im getting it wrong.

This is wrong assumption, "H" should give you Any hex character (0-9, af or AF) .

See the javadoc : MaskFormatter

Also I'd suggest you to have a look at : Implementing a Document Filter

HHHH will make the output hexadecimal. Use AAAAAAA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM