问题
Shouldn't the new Boolean appear as a checkbox? It's showing up as a true/false string value instead. This is how I'm populating the data:
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));
回答1:
Create a subclass ofAbstractTableModel and return Boolean.class in the Method getColumnClass() for the column you want.
回答2:
You need to setup a TableCellRenderer and TableCellEditor
see http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
Once you have defined the render's / editor's you can
define the render/editor as the default render for a Type
table.setDefaultRenderer(Boolean.class, new MyBooleanRender()); table.setDefaultEditor(Boolean.class, new MyBooleanCellEditor());define the render / editor to a column
TableColumnModel tcm = table.getColumnModel(); tcm.getColumn(4).setCellRenderer(new MyBooleanRender()); tcm.getColumn(4).setCellEditor(new MyBooleanCellEditor());
You can define a checkbox cellRender like:
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; } }For a checkboxEditor, you can use the DefaultCellEditor class.
来源:https://stackoverflow.com/questions/27882454/why-is-a-boolean-value-in-jtable-showing-as-true-false-instead-of-a-checkbox