freetowrite. freetospeak. freetodecide.

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 = “`~!@#$%^&amp;*()_+=\\|\”‘:;? / > . < , “;
    @Override
    public void processKeyEvent(KeyEvent ev) {
        char c = ev.getKeyChar();
        if((Character.isLetter(c) &amp;&amp; !ev.isAltDown())
        || badchars.indexOf(c) > -1) {
            ev.consume();
            return;
        }
        if (c == ‘-’ &amp;&amp; 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.




one comment
subscribe to comments

  1. Amri Shodiq

    Jan 17, 2009

    Sebaiknya untuk menampilkan source code pakai plugins yang tepat. Coba lihat di sini.

write a comment


name (required)

email (will not be published) (required)

web/blog

CAPTCHA image