Home >Java >javaTutorial >How to Restrict JTextField Input to Positive Integers Only?
Restricting JTextField Input to Integers
To limit input to positive integers in a JTextField, utilizing a DocumentFilter is recommended over a KeyListener. A DocumentFilter provides a more comprehensive solution that handles various input scenarios.
DocumentFilter Implementation
A DocumentFilter can be implemented to validate input as it is inserted. This example filter, MyIntFilter, checks the entered text to ensure it represents a valid integer:
class MyIntFilter extends DocumentFilter { ... private boolean test(String text) { try { Integer.parseInt(text); return true; } catch (NumberFormatException e) { return false; } } ... }
This filter checks if the input text can be parsed as an integer. If valid, it allows the insertion. Otherwise, it prevents the insertion.
Applying the DocumentFilter
To apply the filter to your JTextField, use the setDocumentFilter method:
PlainDocument doc = (PlainDocument) textField.getDocument(); doc.setDocumentFilter(new MyIntFilter());
Advantages of using a DocumentFilter
The above is the detailed content of How to Restrict JTextField Input to Positive Integers Only?. For more information, please follow other related articles on the PHP Chinese website!