在我的Jtable
中,我有一列boolean
值显示为Checkbox
。我已经添加了Jtable
TableCellRenderer
,以下是代码:
TableCellRenderer tableCellBoolean = new DefaultTableCellRenderer() {
Boolean UserEnterValuse = new Boolean(false);
public Component getTableCellRendererComponent(JTable table,
Boolean value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (value instanceof Boolean) {
UserEnterValuse = Boolean.valueOf(value.toString());
System.out.print(table.getCellRenderer(row, column));
//InstallmentDate.get
table.setValueAt(UserEnterValuse, row, column);
}
return super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
}
};
我还添加了setCellEditor
但是当我单击Jtable
单元格时,它会显示Checkbox
,在选择或更改单元格中的值后,它根据选择类型显示真或假,但不显示我Checkbox
。
如果我不添加TableCellRenderer
并且当我将值设置为单元格Jtable
时,它会给我错误:Object can not cast to Boolean Type
。
首先,
您使用了错误的方法签名。
// wrong
public Component getTableCellRendererComponent(JTable table,
Boolean value, boolean isSelected, boolean hasFocus,
int row, int column) {
// correct
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
要显示复选框,您需要在渲染器中扩展复选框。这是布尔值的正确渲染器(它是来自 JTable 源的略微修改的渲染器)。
public class BooleanRenderer extends JCheckBox implements TableCellRenderer {
private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public BooleanRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
setBorderPainted(true);
}
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;
}
}