`
tuxq5721
  • 浏览: 33316 次
社区版块
存档分类
最新评论

Swing —— 扩展PlainDocument限制JTextField只能输入字母与数字

阅读更多

下面是示例代码: 

[复制源代码]

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

}

}

分享到:
评论
1 楼 jianghongh 2015-10-10  
在存在输入法的情况下,offs值存在问题,这个要怎么解决?

相关推荐

Global site tag (gtag.js) - Google Analytics