the following comes from JDK-HELP:
public class MaskFormatter
extends DefaultFormatter
MaskFormatter is used to format and edit strings. The behavior of a MaskFormatter is controlled by way of a String mask that specifies the valid characters that can be contained at a particular location in the Document model. The following characters can be specified: Character  Description
 
# Any valid number, uses Character.isDigit. 
' Escape character, used to escape any of the special formatting characters. 
U Any character (Character.isLetter). All lowercase letters are mapped to upper case. 
L Any character (Character.isLetter). All upper case letters are mapped to lower case. 
A Any character or number (Character.isLetter or Character.isDigit) 
? Any character (Character.isLetter). 
* Anything. 
H Any hex character (0-9, a-f or A-F). 
Typically characters correspond to one char, but in certain languages this is not the case. The mask is on a per character basis, and will thus adjust to fit as many chars as are needed. You can further restrict the characters that can be input by the setInvalidCharacters and setValidCharacters methods. setInvalidCharacters allows you to specify which characters are not legal. setValidCharacters allows you to specify which characters are valid. For example, the following code block is equivalent to a mask of '0xHHH' with no invalid/valid characters:  MaskFormatter formatter = new MaskFormatter("0x***");
 formatter.setValidCharacters("0123456789abcdefABCDEF");
 
When initially formatting a value if the length of the string is less than the length of the mask, two things can happen. Either the placeholder string will be used, or the placeholder character will be used. Precedence is given to the placeholder string. For example:    MaskFormatter formatter = new MaskFormatter("###-####");
   formatter.setPlaceholderCharacter('_');
   formatter.getDisplayValue(tf, "123");
 
Would result in the string '123-____'. If setPlaceholder("555-1212") was invoked '123-1212' would result. The placeholder String is only used on the initial format, on subsequent formats only the placeholder character will be used. If a MaskFormatter is configured to only allow valid characters (setAllowsInvalid(false)) literal characters will be skipped as necessary when editing. Consider a MaskFormatter with the mask "###-####" and current value "555-1212". Using the right arrow key to navigate through the field will result in (| indicates the position of the caret):    |555-1212
   5|55-1212
   55|5-1212
   555-|1212
   555-1|212
 
The '-' is a literal (non-editable) character, and is skipped. 
Similar behavior will result when editing. Consider inserting the string '123-45' and '12345' into the MaskFormatter in the previous example. Both inserts will result in the same String, '123-45__'. When MaskFormatter is processing the insert at character position 3 (the '-'), two things can happen: If the inserted character is '-', it is accepted. 
If the inserted character matches the mask for the next non-literal character, it is accepted at the new location. 
Anything else results in an invalid edit 
By default MaskFormatter will not allow invalid edits, you can change this with the setAllowsInvalid method, and will commit edits on valid edits (use the setCommitsOnValidEdit to change this). By default, MaskFormatter is in overwrite mode. That is as characters are typed a new character is not inserted, rather the character at the current location is replaced with the newly typed character. You can change this behavior by way of the method setOverwriteMode. Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder. Since: 
1.4 

解决方案 »

  1.   

    http://blog.csdn.net/gdsean/archive/2002/07/03/6329.aspx
    看一下,用JFormattedTextField.
      

  2.   

    import javax.swing.text.*;
    import java.awt.event.*;
    import java.awt.*;public class LimitedTextField extends javax.swing.JTextField
    { protected int _column,
    _length; private String _validValue;
    private String  _validValues; static public final int  ASCII = 0;
    static public final int  NUMBER = 1; private final int       _defaultLength = 31;
    private final String _defaultValue =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789! #$%&'()*+,-./:;<=>?@[]^_`{|}~";
    private final String _numberValue = "0123456789";
    private String _beforeText = ""; // 擖椡晄壜偺暥帤楍傪儁乕僗僩偝傟偨偲偒偵尦偵栠偡偨傔偺暥帤楍 /**
     * 峔抸巕
         * 敿妏塸悢丄惂尷暥帤悢31帤偺僥僉僗僩僼傿乕儖僪
     */
    public LimitedTextField(){ _validValue = _defaultValue;
    _column = _defaultLength; enableEvents( AWTEvent.KEY_EVENT_MASK );
    } /**
     * 峔抸巕
         * 惂尷暥帤悢31帤偺僥僉僗僩僼傿乕儖僪
     * @param columncnt 惂尷暥帤悢
     */
    public LimitedTextField( int columncnt ){ _validValue = _defaultValue;
    _column = columncnt; enableEvents( AWTEvent.KEY_EVENT_MASK );
    }
    /**
     * 峔抸巕
     * @param columncnt 惂尷暥帤悢
     * @param validValue 惂尷暥帤楍
     */
    public LimitedTextField( int columncnt, String validValue ){ _validValue = validValue;
    _column = columncnt; enableEvents( AWTEvent.KEY_EVENT_MASK );
    } /**
         * 僼傿乕儖僪庬暿傪愝掕偡傞
     * @param type  僼傿乕儖僪庬暿乮 ASCII or NUMBER 乯
     */
    public void setFieldType(int type){
    if( type == ASCII ){
    _validValue = _defaultValue;
    }else if( type == NUMBER ){
    _validValue = _numberValue;
    }
    } /**
     * 偙偺TextField偺僋儕傾
     */
    public void clearField(){
    super.setText("");
    _length = 0;
    } /**
     * TextField偐傜僗儁乕僗傪庢傝彍偔
     */
    public void trimField(){
    String text = getText();
    if( text != null ){
    setText(text.trim());
    _length = getText().length();
    }
    } /**
     * TextField偺撪梕傪僄儔乕捈慜偺忬懺偵栠偡
     */
    public void setBeforeText(){
    setText( _beforeText );
    _length = getText().length();
    } private boolean _first = true; /**
     * TextField偺processKeyEvent偺僆乕僶儔僀僪
     * @param event 僉乕僀儀儞僩
     */
    protected void processKeyEvent( KeyEvent event ){
    if( event.getID() == KeyEvent.KEY_RELEASED ){
    //     System.out.println("==> processKeyEvent( KEY_RELEASED )");
    }else{
    //     System.out.println("==> processKeyEvent( NOT KEY_RELEASED )");
    }
    if( _first ){
    _beforeText = getText();
    _first = false;
    }
    int keyCode = event.getKeyCode();
    if( keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_RIGHT ){
    super.processKeyEvent( event );
    return;
    } if( keyCode == KeyEvent.VK_DELETE ){
    super.processKeyEvent( event );
    _length = getText().length();
    return;
    }
    if( keyCode == KeyEvent.VK_X ){
    if( event.isControlDown() ){
    super.processKeyEvent( event );
    _length = getText().length();
    return;
    }
    } boolean flag = checkEvent( event, getText() );
    if( !flag ){
    // System.out.println("Check...1");
    return;
    } // 晄嬶崌懳墳乮OB2-TR24-DQA-050乯 00/10/26 D.Ishida
    // 偙傟偱栤戣側偄丠偐側丠
    if( event.getID() == KeyEvent.KEY_RELEASED ){
    // System.out.println("***first KEY_RELEASED");
    // System.out.println("getText()          =["+getText()+"]");
    // System.out.println("getText().length( )=["+getText().length()+"]");
    _length = getText().length();
    } try{
    if( _length >= _column && event.getKeyChar() >= ' ' && super.getHighlighter( ).getHighlights( ).length == 0 ){
    if( event.getID() == KeyEvent.KEY_RELEASED ){
    if( event.getKeyCode() != KeyEvent.VK_SHIFT ){
    setText(getText().substring(0,_column));
    beepOn();
    }
    }
    // System.out.println("Check...2");
    return;
    }
    }catch(NullPointerException npe){
    if( event.getID() == KeyEvent.KEY_RELEASED ){
    if( event.getKeyCode() != KeyEvent.VK_SHIFT ){
    beepOn();
    }
    }
    // System.out.println("Check...3");
    return;
    }
    boolean hflag = true;
    if( super.getHighlighter( ).getHighlights( ).length == 0 ){
    hflag = false;
    }
    // System.out.println("Highlight Flag = ["+hflag+"]");
    if( getText().length() > _column ){
    setText(getText().substring(0,_column));
    }
    if( event.getID() == KeyEvent.KEY_RELEASED ){
    // System.out.println("***RELEASED***");
    // System.out.println("getText()          =["+getText()+"]");
    // System.out.println("getText().length( )=["+getText().length()+"]");
    _length = getText().length();
    }else if( event.getID() == KeyEvent.KEY_PRESSED && hflag ){
    // System.out.println("***PRESSED & Highlight***");
    // System.out.println("getText()          =["+getText()+"]");
    // System.out.println("getText().length( )=["+getText().length()+"]");
    _length = getText().length();
    }
    super.processKeyEvent( event );
    } protected void beepOn(){
    Toolkit.getDefaultToolkit().beep();
    } protected boolean checkEvent( KeyEvent event, String text ){
    char chr = event.getKeyChar();
    int keyCode = event.getKeyCode();
    //System.out.println("checkEvent keyCode = ["+Integer.toHexString(keyCode)+"]");
    //System.out.println("checkEvent isControlDown = ["+event.isControlDown()+"]");
    if( event.isControlDown() ){
    if( keyCode == KeyEvent.VK_V ){
    if( text.indexOf(KeyEvent.VK_ENTER) > -1 ){
    setBeforeText(); // TextField傪僋儕傾偟側偄偱捈慜偺忬懺偵彂偒栠偡
    // clearField();
    beepOn();
    return false;
    }else{
    //System.out.println("1 checkInputString("+text+") = ["+checkInputString(text)+"]");
    if( !checkInputString(text) ){
    setBeforeText(); // TextField傪僋儕傾偟側偄偱捈慜偺忬懺偵彂偒栠偡
    // clearField();
    beepOn();
    return false;
    }
    }
    }else if( keyCode == KeyEvent.VK_UNDEFINED ){
    // 3夞栚偺僉乕僀儀儞僩偱偙傟偑旘傫偱偔傞丅
    if( !checkInputString(text) ){
    setBeforeText(); // TextField傪僋儕傾偟側偄偱捈慜偺忬懺偵彂偒栠偡
    return false;
    }
    }
    }else{
    //System.out.println("2 checkInputString("+text+") = ["+checkInputString(text)+"]");
    if( !checkInputString(text) ){
    setBeforeText(); // TextField傪僋儕傾偟側偄偱捈慜偺忬懺偵彂偒栠偡
    if( keyCode != KeyEvent.VK_CONTROL ){ // 僐儞僩儘乕儖僉乕埲奜偺応崌偼價乕僾壒傪柭傜偡
    beepOn();
    }
    return false;
    }
    }
    if( chr >= ' ' && _validValue.indexOf( chr ) == -1 ){
    if( event.getID() == KeyEvent.KEY_RELEASED ){
    if( event.getKeyCode() != KeyEvent.VK_SHIFT ){
    trimField(); // 僗儁乕僗傗僞僽偑捛壛偝傟偨偲偒偺偨傔偵僩儕儉偡傞丅
    beepOn();
    }
    }
    return false;
    }else if( text != null && text.trim().equals("") ){ // TextField偺撪梕偑僩儕儉偟偨寢壥丄嬻偵側偭偨応崌
    if( event.getID() == KeyEvent.KEY_RELEASED ){
    if( event.getKeyCode() != KeyEvent.VK_SHIFT ){
    if( text.length() > 0 ){
    char tmpChr = text.charAt(0);
    if( tmpChr >= ' ' && _validValue.indexOf( tmpChr ) == -1 ){
    clearField(); // 擖椡壜擻暥帤楍偵僗儁乕僗偑側偗傟偽TextField傪僋儕傾偡傞丅
    return false;
    }
    }
    }
    }
    }
    if( keyCode != KeyEvent.VK_UNDEFINED ){
    _beforeText = text;
    //System.out.println("_beforeText = "+_beforeText);
    }
    return true;
    } protected boolean checkInputString( String text ){
    if( text != null ){
    if( text.indexOf( KeyEvent.VK_TAB ) > -1 ){
    return false;
    }
    for( int i = 0; i < text.length(); i++ ){
    try{
    char chr = text.charAt(i);
    //System.out.println("忦審1 = ["+(chr >= ' ')+"]  忦審2 = ["+(_validValue.indexOf( chr ) == -1)+"]");
    if( chr >= ' ' && _validValue.indexOf( chr ) == -1 ){
    return false;
    }
    }catch(Exception e){
    return false;
    }
    }
    }else{
    return false;
    }
    return true;
    }}
    lat_dmsEnd = new LimitedTextField(5, "0123456789.");