|
下面是示例代码: |
publicclass PlainDocumentFilter extends PlainDocument{ public final staticchar[] ALPHA_CHARS = { 'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R','S', 'T', 'U', 'V', 'W','X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v', 'w','x', 'y', 'z' }; public final staticchar[] NUMERIC_CHARS = { '0', '1', '2', '3', '4','5', '6', '7', '8','9' }; public final staticchar[] ALPHA_NUMERIC_CHARS = ArrayUtils.addAll(ALPHA_CHARS,NUMERIC_CHARS); private char[] acceptedChars; public PlainDocumentFilter() { this(ALPHA_NUMERIC_CHARS); } public PlainDocumentFilter(char[] acceptedChars) { this.acceptedChars = acceptedChars; } @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { //遍历String中所有字节,判断是否有包含不允许的字符出现 for (int i = 0, len = str.length(); i < len; i++) { if(!ArrayUtils.contains(acceptedChars, str.charAt(i))){ return; } } super.insertString(offs, str, a); } public static void main(String[] args) { JTextField textField = new JTextField(); textField.setDocument(new PlainDocumentFilter()); JFrame frame = new JFrame(); frame.add(textField); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } } |
Swing —— 扩展PlainDocument限制JTextField只能输入字母与数字
最新推荐文章于 2021-08-22 23:42:50 发布