How to use JFormattedTextField allowing only letters and numbers

假装没事ソ 提交于 2019-12-06 14:27:41

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, a-z or A-Z) but im getting it wrong.

This is wrong assumption, "H" should give you Any hex character (0-9, a-f or A-F).

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!