Eri*_*rik 2 java validation swing jformattedtextfield
我有这个代码,无法得到MaskFormatter正确的
maskformatter
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter("HHHHHHH");
} catch (ParseException e) {
e.printStackTrace();
}
txtTroll = new JFormattedTextField(formatter);
Run Code Online (Sandbox Code Playgroud)
我需要任何十六进制字符(0-9,az或AZ)和"H"应该
只给我(0-9,az或AZ),但我错了.
当我输入文字时,只输入大写字母并且它很慢
,当我点击txtTroll所有字母时,它会消失
小智 6
你可以使用我喜欢的另一种解决方案
写ur文档类并使用重写它的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后
将它设置为你的textField文档 this.jTextField1.setDocument(new HexDocument());
我认为这比使用jFormattedTextField更好