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; }}
转载于:https://www.cnblogs.com/caroar/archive/2012/03/12/2391850.html
相关资源:数据结构—成绩单生成器