How to Validate JTable Cell Input for Invalid Values
When defining a JTable column's class type as a specific number subclass, Swing automatically rejects user input that does not fit the type. For example, if the column is defined as Integer.class, double values are rejected.
To achieve the same effect for non-positive values, the setValueAt method can be overridden in the table model. However, this approach alone does not provide visual feedback to the user.
A more complete solution involves using a custom cell editor. One such editor is the PositiveIntegerCellEditor, which extends DefaultCellEditor and overrides the stopCellEditing method to check for negative or zero values. If an invalid value is detected, the editor sets the cell's border to red and cancels the editing process.
<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; this.textField.setHorizontalAlignment(JTextField.RIGHT); } @Override public boolean stopCellEditing() { try { int v = Integer.valueOf(textField.getText()); if (v < 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { textField.setBorder(red); return false; } return super.stopCellEditing(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { textField.setBorder(black); return super.getTableCellEditorComponent( table, value, isSelected, row, column); } }</code>
To use this editor, the table column's cell editor can be set using the following code:
<code class="java">table.getColumnModel().getColumn(columnIndex).setCellEditor(new PositiveIntegerCellEditor(new JTextField()));</code>
The above is the detailed content of How to Validate JTable Cell Input for Non-Positive Integer Values?. For more information, please follow other related articles on the PHP Chinese website!