java如何创建一个只能输入数字的文本框啊?
如果用JFormattedTextField的话,用.getText()读取不到当前文本框的信息啊,应该怎么办?
JTextField可以读取,但是没办法格式化啊
那位大虾能给个比较好的解决方案?谢谢

解决方案 »

  1.   

    给你一个实现类
    package com.css.anli.ex.swing;
    import java.awt.Toolkit;
    import javax.swing.JTextField;
    import javax.swing.text.PlainDocument;
    import javax.swing.text.JTextComponent;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.AttributeSet;
    /**
     * 标题: JAVA扩展开发包<BR></p>
     * 描述: 只输入整数的文本框<BR></p>
     * 版本: Copyright (c) 2003<BR></p>
     * 公司: 中国计算机软件<BR></p>
     * 作者: 何岸 [([email protected])([email protected])]<BR>
     * 版本 1.0<BR>
     */
    public class IntegerField extends JTextField
    {
      public IntegerField()
      {
        super();
        setDocument(new IntegerDocument());
        setValue(0);
      }
      public IntegerField(int value)
      {
        this();
        this.setValue(value);
      }
      public void setValue(int value)
      {
        super.setText(String.valueOf(value));
      }
      public int getValue()
      {
        try
        {
          return Integer.parseInt(super.getText());
        }
        catch(Exception e)
        {
          return 0;
        }
      }  /**
       * @deprecated
       */  public void setText(String t)
      {
        try
        {
          Integer.parseInt(t);
          super.setText(t);
        }
        catch(Exception e){}
      }  private class IntegerDocument extends PlainDocument
      {
        public void insertString(int offset,String s,AttributeSet attributeSet) throws BadLocationException
        {
          boolean canInsert=false;
          try
          {
            Integer.parseInt(s);
            canInsert=true;
          }
          catch(Exception ex){}
          if(true==canInsert)
          {
            super.insertString(offset,s,attributeSet);
          }
        }
      }
    }