JTextField limiting character amount input and accepting numeric only

前端 未结 7 1223

here\'s the code that i have on how to limit the character input length

class JTextFieldLimit extends PlainDocument {
  private int limit;
  // optional uppe         


        
7条回答
  •  春和景丽
    2020-11-28 00:02

    JFormattedTextField

     JTextComponent txt = new JFormattedTextField( new LimitedIntegerFormatter(limit) );
      txt.addPropertyChangeListener("value", yourPropertyChangeListener);
    
    
    import javax.swing.text.DefaultFormatter;
    import java.text.ParseException;
    
    public class LimitedIntegerFormatter extends DefaultFormatter {
    
      static final long serialVersionUID = 1l;
      private int limit;
    
      public LimitedIntegerFormatter( int limit ) {
        this.limit = limit;
        setValueClass(Integer.class);
        setAllowsInvalid(false);
        setCommitsOnValidEdit(true);
      }
      @Override
      public Object stringToValue(String string) throws ParseException {
        if (string.equals("")) return null;
        if (string.length() > limit) throw new ParseException(string, limit);
        return super.stringToValue(string);
      }
    }
    

    yourPropertyChangeListener will be called with

    new PropertyChangeEvent( "value", Integer oldValue, Integer newValue )

    ( oldValue or newValue will be null in "" text case )

    after every valid edit

提交回复
热议问题