一个文本框,在输入内容的时候,如何只输入数字,并且当长度超过6,不让其输入。

解决方案 »

  1.   

    随便写了个,能满足你的需要,细节问题自已看着办吧/*
     * Created on 2005-7-4
     *
     * TODO To change the template for this generated file go to
     * Window - Preferences - Java - Code Style - Code Templates
     */
    package common.test;import javax.swing.*;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.PlainDocument;/**
     * @author chenxw
     *
     * TODO To change the template for this generated type comment go to
     * Window - Preferences - Java - Code Style - Code Templates
     */
    public class MyText extends JFrame {
    private JTextField aText = new JTextField();
    public MyText(){
    aText.setDocument(new customDoc());
    this.getContentPane().add(aText);
    this.setSize(100,100);
    this.setVisible(true);
    }

    class customDoc extends PlainDocument{
    public void insertString(int offs, String str, AttributeSet a) 
    throws BadLocationException {
    for(int i=0;i<str.length();i++){
    if(str.charAt(i)<'0'||str.charAt(i)>'9'){
    return ;
    }
    }
    super.insertString(offs,str,a);
    }
    }
    public static void main(String[] args) {
    MyText mytext = new MyText();
    }
    }
      

  2.   

    看看 javax.swing.JFormattedTextField
      

  3.   

    mandm正解,可以通过继承PlainDocument并override其中的insertString方法实现.楼主可以参看JTextComponent的文档.