我在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());
答案 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;
}
}