Home > Java > javaTutorial > How to Preserve Custom JTable Cell Rendering After Cell Editing?

How to Preserve Custom JTable Cell Rendering After Cell Editing?

Barbara Streisand
Release: 2024-12-06 12:00:32
Original
647 people have browsed it

How to Preserve Custom JTable Cell Rendering After Cell Editing?

Maintaining JTable Cell Rendering After Cell Edit

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?

Addressing the Issue

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) {
        // ...
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template