Léon

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
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;
}
}

 

posted on 2012-03-12 15:19  Léon  阅读(448)  评论(0编辑  收藏  举报