你可以使用我喜欢的另一种解决方案
编写你的 Document 类并使用重写它的insertString
方法regex expr
例子:
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);
}
}
}
然后
像这样将其设置为您的文本字段的文档this.jTextField1.setDocument(new HexDocument());
我认为这比使用 jFormattedTextField 更好