简体   繁体   中英

Swing JTable with custom TableCellRenderer

In my java application I want to set the color and also the behavior when it is selected. For this I wrote a custom implementation of the TableCellRenderer and it is working as I want. But there is something I'm still confused about...

Here is the implementation of the TableCellRenderer :

public class AccountMovementTableCellRenderer extends JLabel implements TableCellRenderer{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean  isSelected, boolean hasFocus, int row, int column){     
        //My implementation here...
        return this;
    }
}

And here the creation of the JTable :

AccountMovementTableCellRenderer accountMovementCellRenderer = new AccountMovementTableCellRenderer();
entryTable = new JTable(entryModel){
    private static final long serialVersionUID = 1L;

    @Override
    public TableCellRenderer getCellRenderer(int row, int column){
        return accountMovementCellRenderer;
    }
};

I create only one instance of my CellRenderer but I was expecting one CellRenderer per cell and I was surprised it is working this way... The content and color is for every cell different but it uses always the same instance of the CellRenderer, so how could this work?

The Component that TableCellRenderer.prepareRenderer returns is reused to render the contents of the JTable - in your case your renderer extends JLabel (you can could have just extended DefaultTableCellRenderer ) - this JLabel is used to paint the contents of the JTable . The prepareRenderer method is used to customize the JLabel for each cell before rendering. To quote Oracle's tutorial on the JTables

You might expect each cell in a table to be a component. However, for performance reasons, Swing tables are implemented differently.

Instead, a single cell renderer is generally used to draw all of the cells that contain the same type of data. You can think of the renderer as a configurable ink stamp that the table uses to stamp appropriately formatted data onto each cell. When the user starts to edit a cell's data, a cell editor takes over the cell, controlling the cell's editing behavior.

单个渲染器实例会根据上面的代码为每个单元格创建一个唯一的自身图像 ,每个图像都将反映该单元格的状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM