Creating a Numeric-Input JTextField

Creating a Numeric-Input JTextField

Validating user input that is typed into a JTextField can becumbersome, especially if the input string must be converted to anumeric value such as an int. By subclassing JTextField, however, andoverriding its processKeyEvent() method, (which was added in Java 1.2)it is very easy to control which types of characters may or may not betyped into the field.

The IntegerTextField class below is a simple example that only allowsa user to enter positive or negative integer values. It consumes anyKeyEvents for letters, unless the ALT key is pressed, in which casethe event may be needed to activate JButton mnemonics. It alsoconsumes all whitespace and punctuation-type characters contained inthe String “`~!@#$%^&*()_+=\|”‘:;?/>.<, ". It allows a minus signonly if it is the first character entered, to signify a negativevalue.

This class could easily be enhanced, perhaps to allow the entry offloating-point numbers or restrict input to non-negative values. Thebasic idea, however, is the same: Process the allowable KeyEvents, andconsume the rest.

 import java.awt.event.KeyEvent;import javax.swing.JTextField;public class IntegerTextField extends JTextField {    final static String badchars        = "`~!@#$%^&*()_+=\|"':;?/>.<, ";    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);    }}
Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved