如何解决JTable中的一列有多个单元格渲染器?
将Boolean.TRUE存储为真实值。然后为错误的值存储一个空字符串。然后,您需要:
a)重写getCellRenderer(…)方法以为单元格中找到的数据返回适当的渲染器。
b)使包含空字符串的单元格不可编辑:
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);
}
};
使用这种方法,不需要自定义渲染器或编辑器。
解决方法
假设我有以下JTable,只要按下一个按钮,就会显示该JTable:
| Name
------+------------
True | Hello World
False | Foo Bar
True | Foo
False | Bar
我想呈现 最初 对JCheckBox 为真的单元格,以及所有 最初为
false的所有单元格不显示任何内容(无JCheckBox)。用户可以选中或取消选中最初为真的单元格中的JCheckBoxes,这会对我创建的图表有所帮助。
现在,我的单元格渲染器在所有单元格中显示JCheckBoxes,包括最初为false的单元格(它显示那些没有复选标记的JCheckBoxes),但我不想在后者中显示任何内容。这是我的代码:
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,int column) {
this.setVisible(false);
return this;
}
}
在该if
语句中,我尝试在使用this.setVisible(false)
之前先使用NoCheckBoxCellRenderer
,但是它没有用。我正在考虑使用多个单元格渲染器来完成此任务。有可能这样做吗?任何建议将不胜感激!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。