请问怎样使JTextField只能输入数字?请各位高手帮帮忙,我是初学者!

解决方案 »

  1.   

    用 JTextField 的子类 JFormattedTextField
      

  2.   

    public class FormattedSample {
      public static void main (String args[]) throws ParseException {
        JFrame f = new JFrame("JFormattedTextField Sample");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = f.getContentPane();
        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
        // Four-digit year, followed by month name and day of month,
        // each separated by two dashes (--)
        DateFormat format = 
          new SimpleDateFormat("yyyy--MMMM--dd");
        DateFormatter df = new DateFormatter(format);
        JFormattedTextField ftf1 = new 
          JFormattedTextField(df);
        ftf1.setValue(new Date());
        content.add(ftf1);
        // US Social Security number
        MaskFormatter mf1 = 
          new MaskFormatter("###-##-####");
        mf1.setPlaceholderCharacter('_');
        JFormattedTextField ftf2 = new 
          JFormattedTextField(mf1);
        content.add(ftf2);
        // US telephone number
        MaskFormatter mf2 = 
          new MaskFormatter("(###) ###-####");
        JFormattedTextField ftf3 = new 
          JFormattedTextField(mf2);
        content.add(ftf3);
        f.setSize(300, 100);
        f.show();
      }
    }
      

  3.   

    使用正则表达式
    \\d
    就OK了
      

  4.   

    http://blog.csdn.net/irvine007/archive/2005/05/13/374235.aspx
    我自嘎写的JNumberTextField类,虽然比较简单,但是应该能够满足你的要求。