JTable with striped background

前端 未结 5 1349
北恋
北恋 2021-02-06 06:14

Using a different background color for odd and even rows is a commonly used trick to improve readability of large tables.

I want to use this effect in Swing\'s JTable.

5条回答
  •  遥遥无期
    2021-02-06 06:29

    You can also use a custom TableCellRenderer which will pick the color for you, with a part of code like this inside:

    if (isSelected) //color remains the same while selected
    {
        lFgColor = table.getSelectionForeground();
        lBgColor = table.getSelectionBackground();
    }
    else
    {
        lFgColor = table.getForeground();
        if (row%2 != 0) //once out of two rows, change color
            lBgColor = table.getBackground();
        else
        {
            //New look and feels like nimbus declare this property, try to use it
            lBgColor = UIManager.getColor("Table.alternateRowColor"); 
            if (lBgColor == null) //If not, choose your own color
                lBgColor = UIManager.getColor("Table.light");
            }
        }
    }
    

    Edit: I missed the fact that you tried that already, and that you need to extend this color to the space without cells. To my knowledge, this is not possible with the current implementation of JTable or JXTable. The highlighters from JXTable are mostly sophisticated renderers, they still cater only to cells.

    To extend the space, the only possibilities I see are:

    • draw it yourself, in your own component.
    • "hack" a way by adding a fake last column, with a custom JTableHeader which wouldn't display the last column header (and a renderer avoiding the grid for this last column). Also, the table resizing mode should be AUTO_RESIZE_LAST_COLUMN, in this case. This is a lot of conditions to make it work, and I'm not really sure it would work anyway.

提交回复
热议问题