import java.awt.*; import java.awt.event.*; import java.text.*; // import java.util.*; // Internationalized numeric data entry. This revision // traps keyPressed() in hopes MSIE will accommodate it. // Comments: mailto:adahlman@jps.net // // While I wrote this myself, the debug process dragged on and // on until I looked at a similar class courtesy of Peter Jakab // and John Akerley. Their code copyright IBM & licensed with // Nilsson & Jakab's book, Designing JavaBeans using VAJ2. public class NumericTextField extends TextField implements KeyListener{ protected static final String numbers = "0123456789"; protected static String firstDigit; static char dsep; static char gsep; static int gsize; public NumericTextField() { this( "", 0 ); } public NumericTextField( int columns ) { this( "", columns ); } public NumericTextField( String text ) { this( text, text.length() ); } public NumericTextField( String text, int columns ) { super( text, columns ); addKeyListener(this); // Internationalize the text field so that it requires a localized // decimal separator (often a comma), but insist that '-' or '+' be // the first digit, regardless of locale. DecimalFormat df = ( (DecimalFormat)NumberFormat.getNumberInstance() ); DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); dsep = dfs.getDecimalSeparator(); char minus = dfs.getMinusSign(); char plus = '+'; firstDigit = String.valueOf(minus) + String.valueOf(plus) + numbers; // Some code to show how the text field is influenced by the default locale... // Locale loc = Locale.getDefault(); // System.out.println("Language and country are: " + loc.getDisplayLanguage() // + " - " + loc.getDisplayCountry() ); // System.out.println("First digit may also be: '" + plus + "' or '" + minus // +"'. The decimal separator is: '" + dsep + "'"); } // implement KeyListener interface (overriding the methods // inherited from Component. Those keys we want to pass // along, to the component or to an ancestor, are not consume()d. public void keyTyped( KeyEvent ev ) { } public void keyReleased(KeyEvent ev ) { } public void keyPressed( KeyEvent ev ) { if( ev.isActionKey() ) return; int ch = (int)ev.getKeyChar(); // pass legal numbers and signs if( getCaretPosition() == 0 ) { if( firstDigit.indexOf(ch) > -1 ) return; } else if( numbers.indexOf(ch) > -1 ) { return; } // pass editing keys if( ch == KeyEvent.VK_BACK_SPACE || ch == KeyEvent.VK_DELETE ) return; // pass only the first dot if( ch == dsep && (getText().indexOf(dsep) < 0) ) return; // reject everything else ev.consume(); } // add/remove methods for KeyListener not needed (provided by Component) }