【问题标题】:Is there any method like getColumnClass in JTable to set row specific data types?有没有像 JTable 中的 getColumnClass 这样的方法来设置行特定的数据类型?
【发布时间】:2012-11-25 12:08:29
【问题描述】:

我有一个包含两列的 JTable:键名和值。在值列中允许有多种数据类型,如下图:

所以在第 1 列中,我可能在第 1 行有一个布尔值,在第 2 行有一个字符串。但是 getColumnClass(...) 方法只允许我为整个列设置数据类型。

有没有办法设置列行特定的数据类型?

您好, 神话

【问题讨论】:

    标签: jtable


    【解决方案1】:

    同一列不能有两种数据类型。但是对于您的情况,我的建议是使用渲染。

    1. 了解Editors and Renderers

    2. 将列数据类型定义为包含JPanel的组件类。

    3. 渲染列。您的 Renderer 类将面板返回到该列。它应该有一个constraint,基于您应该将组件添加到面板并返回面板。

    这个例子展示了如何在这些情况下使用渲染。

    class PanelCellRenderer extends JPanel implements TableCellRenderer {
    public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
           // row number is used as a constraint.
            if(row == 0) {
                this.add( new JTextField("", 20));
            } else if(row == 1) {
                this.add( new JCheckBox());
            } else if(row == 2) {
                this.add( new JButton());
            } else {
                this.add( new JLabel("Row-4"));
            }
            return this;
       }
    }
    

    // 输出:

    第一行是带有JTextField 的面板。 同样,第 2、3 行有 JCheckBoxJButton。 第 4 行有一个 JLabel 和文字。

    P.S:这只是一个尝试。即使我以前没有这样做过。如果我错了,请纠正我。

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 2022-12-21
      相关资源
      最近更新 更多