jtextfield that only accept numbers
here it is a java class made to make your jtextfield accepts only numbers. i’ve found it somewhere in the net. my brother, a java specialist called mamasexy, told me to put the code here in my blog. he said it would help people who need it. that sounds wise.. so i put it here, right here below with a green text.
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class IntTextField extends JTextField {
final static String badchars = “`~!@#$%^&*()_+=\\|\”‘:;?/>.<, “;
@Override
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
if((Character.isLetter(c) && !ev.isAltDown()) || badchars.indexOf(c) > -1) {
ev.consume();
return;
}
if(c == ‘-’ && getDocument().getLength() > 0) ev.consume();
else super.processKeyEvent(ev);
}
}
i use this code with Java 6 using Netbeans IDE 6. you need to include this java class on your package to make it work. dont forget to create textfield’s instance using myTextfield = new IntTextField();.
well..i hope it’s useful… enjoy your cup of java.