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

前端 未结 19 1905
陌清茗
陌清茗 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:07

    A simple approach is to subclass JTextField and override createDefaultModel() by returning customised PlainDocument subclass. Example - a textfield for integers only:

    public class NumberField extends JTextField {
    
    
    @Override
    protected Document createDefaultModel() {
        return new Numberdocument();
    }
    
    class Numberdocument extends PlainDocument
    {
        String numbers="1234567890-";
        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {
            if(!numbers.contains(str));
            else    super.insertString(offs, str, a);
        }
    }
    

    Process input in insertString() any way.

提交回复
热议问题