【问题标题】:How do I retrieve the component type used at a specific cell in a JTable?如何检索 JTable 中特定单元格中使用的组件类型?
【发布时间】: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,无论单元格中包含什么内容,无论是 JCheckBoxJRadioButtonJComboBox... 一切都返回为 null。

是否有其他方法可以获取单元格的组件?或者有没有办法让我让它工作?谢谢!

【问题讨论】:

  • getComponentAt 方法指的是“像素坐标”,而不是表格的单元格。通常,表格的单元格是使用渲染器渲染的,但是这样的渲染器(通常)对一列的 all 单元格使用 same 组件(它的使用类似于 "邮票”,仅用于绘制单元格内容 - 组件并不是真正的“那里”)。您提到您正在渲染器中创建新按钮。这可能会导致问题,因为按钮可能会在每次绘制时重新创建。您应该添加基于按钮的渲染器/编辑器的代码(最好是可编译的示例)
  • @Marco13 是的,你是对的。
  • 使用 JTabel#getCellRenderer 和 TableCellRenderer#getTableCellRendererCoomponent 的组合。这将返回 JTable 使用的物理组件,如果该渲染包含子组件,您将需要进一步检查渲染器组件
  • 引用了几个替代方案here

标签: java jtable jradiobutton buttongroup


【解决方案1】:

如果您有来自table.getModel() 的 tableModel。然后就可以拨打model.getValueAt(row,col)

我不确定您为什么要将 Swing 组件放在 JTable 中。你用它来格式化吗?如果是这样look into LayoutManagers。如果您想编辑表格中的值,您可能需要考虑扩展 TableCellEditor。如果你真的想把组件放在你的桌子上。考虑扩展 DefaultTableCellRenderer 以返回您的组件。你会想要override getTableCellRendererComponent()

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2012-03-05
    • 2021-06-20
    • 1970-01-01
    • 2016-01-04
    • 2017-09-07
    • 2021-11-27
    • 2015-01-28
    相关资源
    最近更新 更多