Preventing Invalid Input in JTable Cells
The JTable component provides built-in validation for certain data types, such as integers. However, it does not handle negative or zero values by default. To implement custom validation rules, you can create a custom cell editor class.
Solution:
Instead of using a TableModel that validates input, create a subclass of DefaultCellEditor as follows:
<code class="java">private static class PositiveIntegerCellEditor extends DefaultCellEditor { private static final Border red = new LineBorder(Color.red); private static final Border black = new LineBorder(Color.black); private JTextField textField; public PositiveIntegerCellEditor(JTextField textField) { super(textField); this.textField = textField; textField.setHorizontalAlignment(JTextField.RIGHT); // Align right for positive numbers } @Override public boolean stopCellEditing() { try { int value = Integer.valueOf(textField.getText()); if (value < 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { textField.setBorder(red); // Highlight invalid input return false; } textField.setBorder(black); // Reset border for valid input return super.stopCellEditing(); } }</code>
This custom editor checks user input and displays a red border for invalid values (negative or zero).
Implementation:
Instantiate the custom editor and set it for the desired column:
<code class="java">JTextField integerField = new JTextField(); PositiveIntegerCellEditor integerEditor = new PositiveIntegerCellEditor(integerField); table.getColumnModel().getColumn(columnIndex).setCellEditor(integerEditor);</code>
This solution mimics the behavior of the default editor for integer input, rejecting negative or zero values and highlighting invalid cells.
The above is the detailed content of How Can I Prevent Negative or Zero Values in JTable Cells?. For more information, please follow other related articles on the PHP Chinese website!