In a previous question, the focus was on formatting a JTable column as a string but with sorting functionality as a double. Following this discussion, a new question arises: How to retain the cell rendering after editing the cell's value?
Specifically, the issue is that after using a custom cell renderer to format the cell, and then implementing a JTextField editor, the custom renderer's formatting is lost after the cell is edited. This begs the question: is the renderer not meant to continue rendering the cells after the initial data display?
Fortunately, it is not a matter of the renderer failing to function as expected. The key lies in understanding the table's editing process. When editing concludes, the table's editingStopped() method retrieves the updated value via getCellEditorValue() and utilizes it to setValueAt() in the model. This, in turn, triggers fireTableCellUpdated(), invoking the prescribed renderer. Therefore, overriding the default renderer should suffice for maintaining the number formatting.
In cases where the implementation demands more flexibility, using an instance of the renderer as the editor component is a viable option. Here's an example:
// ... table.setDefaultRenderer(Double.class, new CurrencyRenderer(nf)); table.setDefaultEditor(Double.class, new CurrencyEditor(nf)); // ... private static class CurrencyEditor extends DefaultCellEditor { // ... @Override public Object getCellEditorValue() { // ... } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { // ... } }
By employing this approach, the custom renderer is utilized both for rendering the cells and facilitating their editing.
The above is the detailed content of How to Preserve Custom JTable Cell Rendering After Cell Editing?. For more information, please follow other related articles on the PHP Chinese website!