why the color is set to all the columns - getTableCellRendererComponent?

33 Views Asked by At

I've got a question here about setBackground() and the below is myRenderer.

    class myRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        String tableName = table.getName();
        displayData(row, column, label, value, tableName);
        return label;
    }
}

This is my displayData method.

private void displayData(int row, int column, JLabel label, Object value, String tableName) {
    switch (tableName) {
        case "ABC":
            addData(row, column, label, value);
            break;
        // other cases...

and this is my other method.

private void addData(int row, int column, JLabel label, Object value){
        if (row == 0 && column == 0) {
        label.setText(value.toString());
        label.setHorizontalAlignment(JLabel.RIGHT);
        ((DefaultTableCellRenderer)label).setBackground(firstColor);
    }
    if (row == 1 && column == 0) {
        label.setText(value.toString());
        label.setHorizontalAlignment(JLabel.RIGHT);
        ((DefaultTableCellRenderer)label).setBackground(secondColor);   
    }

}

I don't really understand why I remove (DefaultTableCellRenderer) from the second if-statement, but it still set the background as firstColor. However, if I set background as secondColor in the second if-statement then I will get a different color. Can someone explain to me the reason?

Thanks.

0

There are 0 best solutions below