【发布时间】:2014-05-16 22:44:34
【问题描述】:
我创建了一个JTable,其列包含各种不同的组件。最后五列要么不包含任何内容(DefaultTableCellRenderer 没有值),要么包含使用自定义渲染器和编辑器的 JRadioButton。渲染器在我需要的单元格中创建并返回一个新的单选按钮,我想从我的面板类访问这些单选按钮以将它们添加到ButtonGroup。我正在使用我编写的以下代码:
protected void setButtonGroups() {
buttonGroups = new ArrayList<ButtonGroup>();
for (int i = 0; i < tableModel.getRowCount(); i++) {
ButtonGroup currentGroup = new ButtonGroup();
for (int j = 0; j < tableModel.getColumnCount(); j++) {
if (table.getComponentAt(i, j) != null) {
currentGroup.add((JRadioButton)table.getComponentAt(i, j));
}
}
}
buttonGroups.add(currentGroup);
}
}
getComponentAt() 不断返回 null,无论单元格中包含什么内容,无论是 JCheckBox、JRadioButton、JComboBox... 一切都返回为 null。
是否有其他方法可以获取单元格的组件?或者有没有办法让我让它工作?谢谢!
【问题讨论】:
-
getComponentAt方法指的是“像素坐标”,而不是表格的单元格。通常,表格的单元格是使用渲染器渲染的,但是这样的渲染器(通常)对一列的 all 单元格使用 same 组件(它的使用类似于 "邮票”,仅用于绘制单元格内容 - 组件并不是真正的“那里”)。您提到您正在渲染器中创建新按钮。这可能会导致问题,因为按钮可能会在每次绘制时重新创建。您应该添加基于按钮的渲染器/编辑器的代码(最好是可编译的示例) -
@Marco13 是的,你是对的。
-
使用 JTabel#getCellRenderer 和 TableCellRenderer#getTableCellRendererCoomponent 的组合。这将返回 JTable 使用的物理组件,如果该渲染包含子组件,您将需要进一步检查渲染器组件
-
引用了几个替代方案here。
标签: java jtable jradiobutton buttongroup