質問

I want to change color of whole row in my JTable.

I defined the JTable:

JTable table = new JTable(data, columnNames);

where data, columnNames are the String tables.

The most common way to do this is to write own class:

public class StatusColumnCellRenderer extends DefaultTableCellRenderer {

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

            //Cells are by default rendered as a JLabel.
            JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

            //Get the status for the current row.

            l.setBackground(Color.GREEN);

            //Return the JLabel which renders the cell.
            return l;
        }
    }

and call:

this.table.getColumnModel().getColumn(0).setCellRenderer(new StatusColumnCellRenderer());

But it is doesn't work. What am I doing wrong?

役に立ちましたか?

解決

You're setting the TableCellRenderer correctly initially but then you're replacing it with this code:

for (int i = 0 ; i < table.getColumnCount(); i++)
   table.getColumnModel().getColumn(i).setCellRenderer( centerRenderer );

Change it so that it sets the colored cell renderer at the correct index (and add braces(!)):

for (int i = 0; i < table.getColumnCount(); i++) {
    TableColumn column = table.getColumnModel().getColumn(i);
    if (i == COLOR_COLUMN) { // COLOR_COLUMN = 1
        column.setCellRenderer(new StatusColumnCellRenderer());
    } else { 
        column.setCellRenderer(centerRenderer);
    }
}

他のヒント

I want to change color of whole row in my JTable.

You are only adding the renderer to the first column so only the first column will be colored, not the entire row.

Check out Table Row Rendering if your actual requirement is to color all columns of the row.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top