【问题标题】:Input text only accepts numbers输入文本只接受数字
【发布时间】:2014-03-26 15:03:21
【问题描述】:

我设计了一个带有一些 JTextFields 的小摇摆 GUI,但它有一个 validateVariables 方法,该方法必须验证接口内的所有字段,有一个称为 (IP) 的 JTextField 必须只接受 int 变量我如何设置它就这样?

P.S JTextfield 是在 netbeans 中使用调色板工具创建的。

【问题讨论】:

    标签: java swing integer jtextfield


    【解决方案1】:

    只需使用DocumentFilter 即可仅接受整数。

    import java.awt.*;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException; 
    import javax.swing.text.DocumentFilter;
    import javax.swing.text.DocumentFilter.FilterBypass;
    
    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);
    }
    }
    

    【讨论】:

      【解决方案2】:

      这是 JTextField 的 javadoc http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html

      有一个例子

      public class UpperCaseField extends JTextField {
      
        public UpperCaseField(int cols) {
          super(cols);
        }
      
        protected Document createDefaultModel() {
          return new UpperCaseDocument();
        }
      
        static class UpperCaseDocument extends PlainDocument {
      
          public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {
      
              if (str == null) {
                return;
              }
              char[] upper = str.toCharArray();
              for (int i = 0; i < upper.length; i++) {
                upper[i] = Character.toUpperCase(upper[i]);
              }
              super.insertString(offs, new String(upper), a);
            }
          }
        }
      

      此示例将所有用户输入更改为大写。 只需修改insertString方法,去掉所有非数字字符, 你可以让你的文本字段只接受数字。

      例子:

      public void insertString(int offs, String str, AttributeSet a)
          throws BadLocationException {
        if (str == null) {
          return;
        }
        super.insertString(offs, str.replaceAll("[^0-9]", ""), a);
      }
      

      ---- 编辑----

      正如@MadProgrammer 所说,DocumentFilter 是另一种方式,例如:

      Document document = someJTextField.getDocument();
      if (document instanceof AbstractDocument) {
        ((AbstractDocument) doc).setDocumentFilter(new DocumentFilter() {
          public void insertString(DocumentFilter.FilterBypass fb, int offset,  
              String str, AttributeSet a) throws BadLocationException {  
            fb.insertString(offset, str.replaceAll("[^0-9]", ""), a);  
          }
        });
      }
      

      【讨论】:

      • 你还需要重写 DocumentFilter 的 replace(...) 方法。
      【解决方案3】:

      使用DocumentFilter,这就是它的设计目的。

      查看Text Component Features,尤其是Implementing a Document Filterhere 示例

      【讨论】:

        【解决方案4】:

        当我正确地记得摆动文本字段时,您可以注册为输入/按键侦听器并在每次击键时验证输入。

        【讨论】:

        • 当您想修改进入该字段的内容时,您永远不应该将KeyListener 注册到文本组件 - 首先您冒着产生异常的风险,其次它无法处理这种情况用户将文本粘贴到字段中的位置。
        猜你喜欢
        • 1970-01-01
        • 2017-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多