Accepting Only Numeric Values in a JTextField
It is possible to limit a JTextField to accept only numeric values by employing the JFormattedTextField class. This class supports validating diverse data types with Format objects.
Using JFormattedTextField for Numeric Input
The JFormattedTextField provides a flexible solution for validating data and offering visual feedback. Here's how to use it for numeric input:
NumberFormat integerNumberInstance = NumberFormat.getIntegerInstance(); ImprovedFormattedTextField integerFormattedTextField = new ImprovedFormattedTextField(integerNumberInstance, 100);
In this example:
Custom Formatter for Complete Parsing
To ensure that only complete numeric values are accepted, we can use the ParseAllFormat class as a decorator for the format object:
final Format format = new ParseAllFormat(integerNumberInstance);
This wrapper format ensures that if a partial numeric value is entered, the value will be rejected.
Additional Features of ImprovedFormattedTextField
The ImprovedFormattedTextField class offers several additional features:
Example Usage
To incorporate the numeric input functionality into a GUI:
JPanel panel = new JPanel(new BorderLayout()); panel.add(integerFormattedTextField, BorderLayout.WEST); JButton button = new JButton(new AbstractAction() { { integerFormattedTextField.addPropertyChangeListener("editValid", event -> setEnabled((Boolean) event.getNewValue())); putValue(Action.NAME, "Show Current Value"); } @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "The current value is [" + integerFormattedTextField.getValue() + "]"); } });
This setup initializes a numeric text field with the improved behavior. The button displays the value and is only enabled when the input is valid.
The above is the detailed content of How Can I Restrict a JTextField to Accept Only Numeric Input in Java?. For more information, please follow other related articles on the PHP Chinese website!