开发者

JTable TableCellRenderer background with NimbusLookAndFeel color problem

开发者 https://www.devze.com 2023-03-17 07:53 出处:网络
I\'m using NimbusLookAndFeel. With this look and feel JTable\'s cell background are alternatively whi开发者_如何学Pythonte and light grey (it depends on the row number).

I'm using NimbusLookAndFeel. With this look and feel JTable's cell background are alternatively whi开发者_如何学Pythonte and light grey (it depends on the row number). Now, I'm writing some custom cell renderer implementing TableCellRenderer. I need to set the background of these renderers according to the position of the cell in the JTable.

public class MyCellRenderer extends JLabel implements TableCellRenderer{


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

                Color bgColor = //need to retrieve the right cell background color
                setBackground(bgColor);
        return this;
    }

}

How can I get such a Color value?


Technically, you can access the color via the UIManager

   Color alternate = UIManager.getColor("Table.alternateRowColor");

Practically, I would not recommend to write renderers from scratch - there are many details to consider to get it right. Those details are handled f.i. in SwingX (biased me :-)

Expected you to do the logic yourself ;-). Here's a working snippet (assuming you want to color by row not by column, but changing that would be ... trivial):

    TableCellRenderer renderer = new TableCellRenderer() {

        JLabel label = new JLabel();

        @Override
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus,
                int row, int column) {
            label.setOpaque(true);
            label.setText("" + value);
            Color alternate = UIManager.getColor("Table.alternateRowColor");
            if (row % 2 == 1) {
                label.setBackground(alternate);
            } else {
                label.setBackground(Color.WHITE);
            }
            return label;
        }

    };
    table.setDefaultRenderer(Object.class, renderer);


This should work perfectly :

public class MyRenderer extends DefaultTableCellRenderer { ... }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号