如何使用JFormattedTextField只允许字母和数字

我有这个代码,无法正确使用MaskFormatter
MaskFormatter之外

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

我需要任何hex字符(0-9,az或AZ)和“H”应该
只给我(0-9,az或AZ),但我错了。

当我输入文字时,只输入大写字母并且输入速度很慢
当我点击txtTroll所有字母都会消失

你可以使用我喜欢的另一种解决方案

写ur文档类,并使用regex expr重写它的insertString方法

例:

 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); } } } 

然后

将它设置为你的textField文件,如this.jTextField1.setDocument(new HexDocument());

我认为这比使用jFormattedTextField更好

你的假设存在一些问题,确保你需要什么,如果你需要字母和数字,HEX 不是你需要的,

“H”应该只给我(0-9,az或AZ),但我错了。

这是错误的假设,“H”应该给你任何hex字符(0-9,af或AF)

请参阅javadoc: MaskFormatter

另外我建议你看看: 实现文档filter

HHHH将输出为hex。 使用AAAAAAA