将 JPanel 行添加到 JTable 模型

Adding a JPanel row to a JTable model

我正在尝试将一个 jpanel 作为一行添加到我的 jtable,如下所示: table ,在点击右上角的编辑按钮之前,红色按钮应该是不可见的。

我试过这样的事情:

JPanel row = new JPanel();
            row.setBackground(new Color(255, 255, 255, 0));
            row.setAutoscrolls(true);
            row.setBorder(new EmptyBorder(0, 0, 0, 0));
            row.setLayout(new TableLayout(new double[][]{
                    {TableLayout.FILL, TableLayout.FILL},
                    {TableLayout.PREFERRED}}));
            ((TableLayout)row.getLayout()).setHGap(0);
            ((TableLayout)row.getLayout()).setVGap(0);

            JLabel deleteRow = new JLabel();
            deleteRow.setText("");
            deleteRow.setIcon(new ImageIcon(getClass().getResource("/com/example/clinicsystem/pictures/remove.png")));
            JLabel rowText = new JLabel();
            rowText.setText(comboBoxPermissions.getSelectedItem().toString());
            rowText.setForeground(Color.black);
            rowText.setFont(new Font("Helvetica-Normal", Font.PLAIN, 14));
            rowText.setHorizontalAlignment(SwingConstants.CENTER);

            row.add(deleteRow, new TableLayoutConstraints(0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
            row.add(rowText, new TableLayoutConstraints(0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

            model.addRow(new JPanel[]{row});

但是当我 运行 项目时,我在该面板应该所在的行中得到了这个文本:

javax.swing.JPanel[,0,0,0x0,invalid,layout=info.clearthought.layout.TableLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.border.EmptyBorder@254d8187,flags=33554441,maximumSize=,minimumSize=,preferredSize=]

I get this text inside the row where this panel is supposed to be:

默认情况下,table 的呈现器将简单地对 TableModel 中的数据调用 toString() 方法,因此您会看到 JPanel 的 toString() 值。

A JTable 不是为向 TableModel 添加组件而设计的。它专为您向 TableModel 添加数据而设计。然后根据添加到模型的数据类型呈现数据。

the red buttons are supposed to be invisible till the edit button on the top right is clicked.

因此您需要添加一列数据来表示红色按钮。从阅读 Table Button Column 开始。它演示了如何向 table 添加一列按钮以及如何添加单击按钮时要调用的操作。

如果您不希望该列可见,则可以在创建 table 后从 TableColumnModel 中删除 TableColumn。然后当 "edit" 按钮被点击时,你可以将 TableColumn 添加回 TableColumnModel

TableColumnModel 有像 removeTableColumn(...)addTableColumn(..) 这样的方法来帮助解决这个问题。您还可以使用 JTable 的 getColumn(...) 方法来获取要删除的列并保存以备将来使用。

阅读 How to Use Table 上的 Swing 教程部分,了解有关渲染器和编辑器的更多信息。