Reputation: 5354
Let's say I have the following JTable, which is displayed as soon as a button is pressed:
| Name
------+------------
True | Hello World
False | Foo Bar
True | Foo
False | Bar
I want to render the cells that were initially true to a JCheckBox, and all cells that were initially false to not display anything (no JCheckBox). The user could check or un-check the JCheckBoxes in the cells that were initially true, which would do something to a chart I created.
Right now, my cell renderer displays JCheckBoxes in all cells, including those that were initially false (it displays those JCheckBoxes without check marks), but I want to not display anything in the latter. Here is my code:
protected class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (!(Boolean) tableModel.getValueAt(row, 0)) {
NoCheckBoxCellRenderer renderer = new NoCheckBoxCellRenderer();
return renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
this.setSelected((Boolean) tableModel.getValueAt(row, 0));
return this;
}
}
protected class NoCheckBoxCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
this.setVisible(false);
return this;
}
}
In the if
statement, I tried using this.setVisible(false)
before using NoCheckBoxCellRenderer
, but it wasn't working. I'm thinking about using multiple cell renderers to accomplish this task. Would it be possible to do so? Any advice would be greatly appreciated!
Upvotes: 3
Views: 5503
Reputation: 324098
Store Boolean.TRUE for the true values. Then store an empty String for the false values. You will then need to:
a) override the getCellRenderer(...) method to return the appropriate renderer for the data found in the cell.
b) make the cells containing the empty string non-editable:
JTable table = new JTable(data, columnNames)
{
public TableCellRenderer getCellRenderer(int row, int column)
{
if (column == 0)
{
Class cellClass = getValueAt(row, column).getClass();
return getDefaultRenderer( cellClass );
}
return super.getCellRenderer(row, column);
}
public boolean isCellEditable(int row, int column)
{
Class cellClass = getValueAt(row, column).getClass();
if (column == 0 && cellClass instanceof Boolean)
{
return true;
}
else
{
return false;
}
return super.isCellEditable(row, column);
}
};
Using this approach there is no need for custom renderers or editors.
Upvotes: 5
Reputation: 2112
Have getTableCellRendererComponent
return a blank JLabel if the initial value was false.
Upvotes: 3