Maintaining JTable Cell Rendering After Cell Edit
One may encounter the situation where a JTable cell's custom rendering format (e.g., currency formatting) is lost after cell editing. This issue arises because by default, the editing process directly updates the table model, bypassing the custom renderer.
Solution
To resolve this, one can extend the table's setValueAt() method to ensure that the custom renderer is applied to the updated cell value. Here's an example:
table.setValueAt(newValue, rowIndex, columnIndex); ((TableModel) table.getModel()).fireTableCellUpdated(rowIndex, columnIndex);
Alternatively, one can create a custom CellEditor that utilizes the custom renderer as its editor component. By doing so, the editor can apply the custom formatting to the value during editing, and the renderer can display the formatted value after editing is complete.
Example
The following code demonstrates a custom CurrencyEditor that uses a CurrencyRenderer:
public class CurrencyEditor extends DefaultCellEditor { private JTextField textField; public CurrencyEditor() { super(new JTextField()); textField = (JTextField) this.getComponent(); textField.setHorizontalAlignment(JTextField.RIGHT); textField.setBorder(null); } @Override public Object getCellEditorValue() { try { return new Double(textField.getText()); } catch (NumberFormatException e) { return Double.valueOf(0); } } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { textField.setText((value == null) ? "" : CurrencyRenderer.format(value)); return textField; } }
public class CurrencyRenderer extends DefaultTableCellRenderer { private static DecimalFormat formatter = new DecimalFormat("$###,##0.00"); public CurrencyRenderer() { this.setHorizontalAlignment(JLabel.RIGHT); } @Override public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } public static String format(Object value) { return formatter.format(value); } }
By using the provided examples, you can maintain the custom cell rendering after cell editing in a JTable.
The above is the detailed content of How to Preserve Custom JTable Cell Rendering After Editing?. For more information, please follow other related articles on the PHP Chinese website!