Limiting Textfields in Java

后端 未结 4 588
暗喜
暗喜 2021-01-20 00:42

Is there a way to limit a textfield to only allow numbers 0-100, thereby excluding letters, symbols and such as well? I have found a way, but it is way more complicated than

相关标签:
4条回答
  • 2021-01-20 01:06

    You can set a DocumentFilter of the PlainDocument used by the JTextField. The methods of the DocumentFilter will be called before the content of the Document is changed and can complement or ignore this changes:

        PlainDocument doc = new PlainDocument();
        doc.setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
            throws BadLocationException {
                if (check(fb, offset, 0, text)) {
                    fb.insertString(offset, text, attr);
                }
            }
            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
                if (check(fb, offset, length, text)) {
                    fb.replace(offset, length, text, attrs);
                }
            }
            // returns true for valid update
            private boolean check(FilterBypass fb, int offset, int i, String text) {
                // TODO this is just an example, should test if resulting string is valid
                return text.matches("[0-9]*");
            }
        });
    
        JTextField field = new JTextField();
        field.setDocument(doc);
    

    in the above code you must complete the check method to match your requirements, eventually getting the text of the field and replacing/inserting the text to check the result.

    0 讨论(0)
  • 2021-01-20 01:11

    If you must use a text field you should use a JFormattedTextField with a NumberFormatter. You can set the minimum and maximum values allowed on the NumberFormatter.

    NumberFormatter nf = new NumberFormatter();
    nf.setValueClass(Integer.class);
    nf.setMinimum(new Integer(0));
    nf.setMaximum(new Integer(100));
    
    JFormattedTextField field = new JFormattedTextField(nf);
    

    However, Johannes suggestion of using a JSpinner is also appropriate if it suits your use case.

    0 讨论(0)
  • 2021-01-20 01:12

    you must implement and add a new DocumentListener to your textField.getDocument(). I found an implementation here.

    0 讨论(0)
  • 2021-01-20 01:20

    I'd suggest you should go with a JSpinner in this case. Text fields are pretty complicated to work with in Swing since even the most basic single-line ones have a full-blown Document class behind them.

    0 讨论(0)
提交回复
热议问题