Saturday, January 20, 2007

JTextField only digit


// Add feature to JTextField
// MyJTextField.java
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;


public class MyJTextField extends JTextField {

/** Creates a new instance of JOnlyDigitField */
public MyJTextField() {
initFeature();
}

public MyJTextField(int width) {
super(width);
initFeature();
}

int length = 9; // real 10
JTextField txfThis = this;

public void setLength(int length) {
this.length = length - 1;
}

public int getLength() {
return length;
}

public void initFeature() {
this.addKeyListener(new KeyAdapter() {

public void keyTyped(KeyEvent e) {

char c = e.getKeyChar();

if ((!(Character.isDigit(c)
|| c == KeyEvent.VK_BACK_SPACE)
|| (c == KeyEvent.VK_DELETE))) {
e.consume();
}

if (txfThis.getText().length() > length)
e.consume();
}
});
}

}

No comments:

Post a Comment