JTable TableCellRenderer background with NimbusLookAndFeel color problem

时间秒杀一切 提交于 2019-12-23 18:52:06

问题


I'm using NimbusLookAndFeel. With this look and feel JTable's cell background are alternatively white 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?


回答1:


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



回答2:


This should work perfectly :

public class MyRenderer extends DefaultTableCellRenderer { ... }


来源:https://stackoverflow.com/questions/6571877/jtable-tablecellrenderer-background-with-nimbuslookandfeel-color-problem

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