下面是示例代码: |
[复制源代码] |
public class PlainDocumentFilter extends PlainDocument{ public final static char[] 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 static char[] NUMERIC_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8','9' }; public final static char[] 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); } } |