简体   繁体   中英

Set background color for a cell specified in JTable

I'm trying to define a color of a cell in JTable passing line parameters and column and the desired color to color . However the implemented way he paints the specific point the entire column.

    ...        
    table.getColumnModel().getColumn(2).
          setCellRenderer(new CellRenderer(3,2,new Color(24,65,87)));

class CellRenderer extends DefaultTableCellRenderer {

    private static final long serialVersionUID = 1L;
    private Integer row;
    private Integer col;
    private Color color;

    public CellRenderer(Integer row, Integer col, Color color) {
        this.row = row;
        this.col = col;
        this.color = color;
    }

    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int col) {

        Component c = super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, col);

        if(this.row == row && this.col == col){
            c.setBackground(this.color);
        }

        return c;
    }
}

A cell renderer is used for ALL the cells for a given column or object type. You need to supply some object which maintains the information you to use so the renderer can make its decisions about what to highlight

Or use the JXTable from SwingLabs SwingX library which had highlighting functionality

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