Home >Java >javaTutorial >How to Maintain JTable Cell Rendering After a Cell Edit?
After setting up a JTable column as a String and sorting it as a Double, the custom cell renderer initially formatting the column as $###,##0.00 stops rendering the cells after the value is edited.
When a cell is edited, the following events occur in sequence:
To maintain the cell rendering after the edit, the following steps are necessary:
Here is a basic example using the default editor and renderer implementations:
import javax.swing.DefaultCellEditor; import javax.swing.DefaultTableCellRenderer; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import java.text.NumberFormat; public class RenderEditNumber { public static void main(String[] args) { NumberFormat nf = NumberFormat.getCurrencyInstance(); DefaultTableModel model = new DefaultTableModel( new String[]{"Amount"}, 0) { @Override public Class<?> getColumnClass(int columnIndex) { return Double.class; } }; for (int i = 0; i < 16; i++) { model.addRow(new Object[]{Double.valueOf(i)}); } JTable table = new JTable(model); table.setPreferredScrollableViewportSize(new Dimension(123, 123)); table.setDefaultRenderer(Double.class, new CurrencyRenderer(nf)); table.setDefaultEditor(Double.class, new CurrencyEditor(nf)); } private static class CurrencyRenderer extends DefaultTableCellRenderer { private NumberFormat formatter; public CurrencyRenderer(NumberFormat formatter) { this.formatter = formatter; this.setHorizontalAlignment(JLabel.RIGHT); } @Override public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } } private static class CurrencyEditor extends DefaultCellEditor { private NumberFormat formatter; private JTextField textField; public CurrencyEditor(NumberFormat formatter) { super(new JTextField()); this.formatter = formatter; this.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) ? "" : formatter.format((Double) value)); return textField; } } }
In this example, the CurrencyRenderer and CurrencyEditor classes extend the default renderer and editor implementations, respectively, to handle Number formatting. Note that this example does not include the fireTableCellUpdated() call as it is handled internally by the JTable.
The above is the detailed content of How to Maintain JTable Cell Rendering After a Cell Edit?. For more information, please follow other related articles on the PHP Chinese website!