Limiting text fields in Java

Is there a way to limit the text box to only numbers 0-100, thereby excluding letters, characters, and so on? I found a way, but it is much more complicated than it seems necessary.

+4
source share
4 answers

If you must use a text field, you must use a JFormattedTextField with NumberFormatter . You can set the minimum and maximum values โ€‹โ€‹allowed for 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 to use JSpinner is also suitable if it is suitable for your use.

+10
source

I would advise you to go with JSpinner in this case. Text fields are quite difficult to work with Swing, since even the most basic single-line fields have a full-blown Document class behind them.

+5
source

You can set the DocumentFilter to the PlainDocument used by the JTextField. DocumentFilter methods will be called before changing the contents of the Document and may complement or ignore these 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 have to fill in the check method so that it meets your requirements, eventually getting the field text and replacing / inserting the text to check the result.

+1
source

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

0
source

Source: https://habr.com/ru/post/1299428/


All Articles