Jtable setDefaultRenderer在单元格中消失了复选框

时间:2013-07-24 16:00:50

标签: java swing jtable tablecellrenderer

我在JTable中有一个布尔列,所以每个单元格都有一个复选框。当我尝试设置单元格渲染器以更改背景颜色时,单元格中的复选框被值替换(true,false)..什么是错误的!

我的细胞渲染器:

class BackgroundTableCellRenderer extends DefaultTableCellRenderer {

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

        Component c = super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, col); 
        if(row%2 == 0)
        {
            Color bColor = Color.decode("#EFF2ED");
            c.setBackground(bColor);  
        }
        else
            c.setBackground(Color.white);

        return c;
    }
}

我像这样设置渲染器:

data_table.setDefaultRenderer(Boolean.class, new BackgroundTableCellRenderer());

1 个答案:

答案 0 :(得分:4)

  • 使用prepareRenderer进行行装饰

  • (Xxx)TableCellRenderer您可以尝试使用

   class BooleanRenderer extends JCheckBox implements TableCellRenderer, UIResource {

        private static final long serialVersionUID = 1L;
        private final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);

        BooleanRenderer() {
            super();
            setHorizontalAlignment(JLabel.CENTER);
            setBorderPainted(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                super.setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            }
            setSelected(value != null && ((Boolean) value).booleanValue());
            if (hasFocus) {
                setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
            } else {
                setBorder(noFocusBorder);
            }
            return this;
        }
    }