新布尔值不应显示为复选框吗?它反而显示为真/假字符串值。这就是我填充数据的方式:
Object[] columnNames4 = {"Name", "City", "Checkbox"};
Object[][] data = {
{"john smith",
"x", new Boolean(false)},
{"jenny m",
"y", new Boolean(false)}
};
JTable table4 = new JTable(data, columnNames4);
JScrollPane S3 = new JScrollPane(table4);
S3.setPreferredSize(new Dimension(300, 300));
答案 0 :(得分:1)
创建AbstractTableModel的子类,并在Method getColumnClass()中返回所需列的Boolean.class。
答案 1 :(得分:0)
您需要设置TableCellRenderer和TableCellEditor
请参阅http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
一旦定义了渲染/编辑器,您就可以
将渲染/编辑器定义为Type的默认渲染
table.setDefaultRenderer(Boolean.class, new MyBooleanRender());
table.setDefaultEditor(Boolean.class, new MyBooleanCellEditor());
将渲染/编辑器定义为列
TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(4).setCellRenderer(new MyBooleanRender());
tcm.getColumn(4).setCellEditor(new MyBooleanCellEditor());
您可以定义一个复选框cellRender,如:
public class MyBooleanRender extends JCheckBox
implements TableCellRenderer {
private JCheckBox checkBox = this;
/**
* @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent
* (javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(
JTable tbl,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
boolean val = false;
if (Common.isEmpty(value)) {
checkBox.setSelected(false);
} else {
try {
val = ((Boolean) value).booleanValue();
} catch (Exception e) {
}
checkBox.setSelected(val);
}
if (Common.OPTIONS.highlightEmpty.isSelected() && value == Common.MISSING_VALUE) {
checkBox.setBackground(Common.EMPTY_COLOR);
} else if (value == Common.MISSING_REQUIRED_VALUE) {
checkBox.setBackground(Common.MISSING_COLOR);
} else {
...
}
checkBox.setSelected(val);
return checkBox;
}
}
对于checkboxEditor,您可以使用DefaultCellEditor类。