在网上Google了一下,基本上的做法有两种,第一种是JFormattedTextField;另外一种是自己继承PlainDocument,
Override
insertString方法,然后用JTextFiled.setDocument的方法放入自己继承的对象实例。但是最终我都没有采用这两种方法,首
先我对JFormattedTextField的方式不太舒服,然后感觉继承PlainDocument有点太重,所以自己考虑了一种方案,也许有人跟我
的想法雷同,那就纯属巧合了。
下面放上代码:
public class MyJTextField extends JTextField {
private int limit = Integer.MAX_VALUE;
private boolean numberOnly;
public MyJTextField() {
addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (getText().length() + 1 > limit) {
deleteInputChar(e);
return;
}
if (numberOnly) {
char input = e.getKeyChar();
if (!Character.isDigit(input)) {
deleteInputChar(e);
}
}
}
private void deleteInputChar(KeyEvent source) {
source.setKeyChar((char) KeyEvent.VK_CLEAR);
}
});
}
public void setMaxTextLength(int limit) {
if (limit < 0) {
return;
}
this.limit = limit;
}
public int getMaxTextLength() {
return limit;
}
public void setNumberOnly(boolean numberOnly) {
this.numberOnly = numberOnly;
}
public boolean isNumberOnly() {
return this.numberOnly;
}
}
整个思路很简单,就是检查Type事件,如果超出了限制就删除新增加的字符,如果设置了只是数字,那么不是数字的就删除新增加的字符。使用的时候只需要
MyJTextField textField = new MyJTextField();
textField.setLimit(8);
textField.setNumberOnly(true);
结果就是最多输入8个字符而且只能是数字。
posted on 2007-09-09 00:41
ruislan 阅读(1276)
评论(2) 编辑 收藏