怎么可是使在JTextField输入字符控制在10个之内啊??

解决方案 »

  1.   

    最简单的演示:import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;public class TextFieldTest extends JFrame
    {
    public TextFieldTest() {
    setSize( 400,400 );
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); JTextField text = new JTextField();
    text.setDocument( new NumberDocument(text) );
    getContentPane().add( text,BorderLayout.NORTH ); setVisible( true );
    } class NumberDocument extends PlainDocument
    {
    JTextField text = null; NumberDocument( JTextField text ) {
    this.text = text;
    } public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    if( (null == str)|| ("".equals(str)) ) return; StringBuffer sb = new StringBuffer();
    sb.append( text.getText() );
    sb.insert( offs,str );
    try{
    if( sb.length() <= 10 ){
    super.insertString(offs, str, a);
    }
    }catch (NumberFormatException ex){}
    }
    } public static void main( String args[] ) {
    new TextFieldTest();
    }
    }