Is there any way to accept only numeric values in a JTextField?

前端 未结 19 2273
陌清茗
陌清茗 2020-11-22 03:10

Is there any way to accept only numeric values in a JTextField? Is there any special method for this?

19条回答
  •  礼貌的吻别
    2020-11-22 04:06

    Concidering the number of views this question is getting, i found none of the above solution suitable for my problem. I decided to make a custom PlainDocument to fit my needs. This solution also makes a beep sound when the maximum number of characters used is reached, or the inserted text is not an integer.

    private class FixedSizeNumberDocument extends PlainDocument
    {
        private JTextComponent owner;
        private int fixedSize;
    
        public FixedSizeNumberDocument(JTextComponent owner, int fixedSize)
        {
            this.owner = owner;
            this.fixedSize = fixedSize;
        }
    
        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException
        {
            if (getLength() + str.length() > fixedSize) {
                str = str.substring(0, fixedSize - getLength());
                this.owner.getToolkit().beep();
            }
    
            try {
                Integer.parseInt(str);
            } catch (NumberFormatException e) {
                // inserted text is not a number
                this.owner.getToolkit().beep();
                return;
            }
    
            super.insertString(offs, str, a);
        }               
    }
    

    implented as follows:

        JTextField textfield = new JTextField();
        textfield.setDocument(new FixedSizeNumberDocument(textfield,5));
    

提交回复
热议问题