How to change color of row in JTable

纵饮孤独 提交于 2020-01-15 12:21:46

问题


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?


回答1:


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);
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/16882902/how-to-change-color-of-row-in-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!