【问题标题】:Maximum length of JTextField and only accepts numbers?JTextField 的最大长度并且只接受数字?
【发布时间】:2014-02-05 06:37:10
【问题描述】:

我希望用户最多输入 8 个数字,因为它是一个手机号码字段。 这是我的 JTextField。

    txtMobile = new JTextField();
    txtMobile.setColumns(10);
    txtMobile.setBounds(235, 345, 145, 25);
    add(txtMobile);

当我们这样做时,我如何检查 JTextField 中的 >> '^%$* 等无效字符?

1)Maximum Length

2)Accepts only numbers

3)Check for invalid characters

4)Check if it's a valid email address

请帮忙:D

【问题讨论】:

    标签: email numbers character max jtextfield


    【解决方案1】:

    您可以使用JFormattedField,查看How to Use Formatted Text Fields,但它们往往不会限制用户输入他们想要的任何内容,而是对值进行后验证以查看是否满足格式的需求你确定

    您可以改用DocumentFilter,这样您就可以实时过滤输入。

    Implementing a Document FilterMDP's Weblog 为例

    【讨论】:

      【解决方案2】:

      看看这个示例,它只接受数字作为输入,作为你第二个要求的答案。

      public class InputInteger
      {
      private JTextField tField;
      private JLabel label=new JLabel();
      private MyDocumentFilter documentFilter;
      
      private void displayGUI()
      {
          JFrame frame = new JFrame("Input Integer Example");
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      
          JPanel contentPane = new JPanel();
          contentPane.setBorder(
              BorderFactory.createEmptyBorder(5, 5, 5, 5));
          tField = new JTextField(10);
          ((AbstractDocument)tField.getDocument()).setDocumentFilter(
                  new MyDocumentFilter());
          contentPane.add(tField); 
          contentPane.add(label);
      
      
          frame.setContentPane(contentPane);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
      }
      public static void main(String[] args)
      {
          Runnable runnable = new Runnable()
          {
              @Override
              public void run()
              {
                  new InputInteger().displayGUI();
              }
          };
          EventQueue.invokeLater(runnable);
      }
      }
      
      class MyDocumentFilter extends DocumentFilter{
          private static final long serialVersionUID = 1L;
          @Override
      public void insertString(FilterBypass fb, int off
                          , String str, AttributeSet attr) 
                                  throws BadLocationException 
      {
          // remove non-digits
          fb.insertString(off, str.replaceAll("\\D++", ""), attr);
      } 
      @Override
      public void replace(FilterBypass fb, int off
              , int len, String str, AttributeSet attr) 
                              throws BadLocationException 
      {
          // remove non-digits
          fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-22
        • 2017-09-14
        • 1970-01-01
        • 1970-01-01
        • 2013-01-16
        • 1970-01-01
        • 2017-02-10
        • 2018-12-28
        相关资源
        最近更新 更多