仅将 JButton 添加到 JTable 中的某些行和列

Add JButtons only to certain rows and columns in a JTable

我想将一些 JButton 添加到 JTable,但仅限于特定的单元格。 到目前为止,我已经写了一个 class ,它只能将按钮添加到一行。 我找到了很多关于如何将按钮添加到整列的教程,但我不知道如何只将它们添加到某些行。

这就是我想要 table 的样子:

理想的解决方案是,如果我可以根据 table 数据的值添加按钮。例如,如果数据包含一个空字符串,我不会显示一个按钮,如果它有一个正确的值,该字符串将是按钮的文本。

源代码

Class 连接面板

public class ConnectionPanel extends JFrame{

public ConnectionPanel(){

    Object[][] licData = {{"License 1", "0.0.0.0", "connect", "disconnect", ""},{"License 2", "123.123.123", "", "", ""},{"License 3", "42.23.4", "connect", "disconnect", "delete"}};

    ConnTableModel licConnModel = new ConnTableModel(licData);

    this.setLayout(new MigLayout("", "[grow]", "[][grow][][][][][][][grow][][][][][]"));
    this.setSize(new Dimension(500, 300));
    JLabel lblLicenses = new JLabel("Licenses");
    this.add(lblLicenses, "cell 0 0,growx");

    JTable licenseTable = new JTable(licConnModel);
    licenseTable.setTableHeader(null);

    new ButtonColumn(licenseTable, 2, 0);
    new ButtonColumn(licenseTable, 3, 0);
    new ButtonColumn(licenseTable, 2, 2);
    new ButtonColumn(licenseTable, 3, 2);
    new ButtonColumn(licenseTable, 4, 2);

    JScrollPane scrollPaneLic = new JScrollPane();
    scrollPaneLic.setViewportView(licenseTable);
    this.add(scrollPaneLic, "cell 0 1 1 6,grow");
}

内部静态ClassConnTableModel

public static class ConnTableModel extends AbstractTableModel {
    Object[][] data;

    public ConnTableModel(Object[][] data){
        this.data = data;
    }

    @Override
    public int getRowCount() {
        return data.length;
    }

    @Override
    public int getColumnCount() {
        return data[0].length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) { 
        if(columnIndex == 2 || columnIndex == 3 || columnIndex == 4) {
            return true;
        } else {
            return false;
        }
    }   
}

内部Class ButtonColumn

class ButtonColumn extends AbstractCellEditor
implements TableCellRenderer, TableCellEditor, ActionListener
{
    JTable table;
    JButton editButton;
    JButton renderButton;
    String text;
    int showRow;

    public ButtonColumn(JTable table, int column, int showRow) {
        super();
        this.table = table;
        this.showRow = showRow;
        renderButton = new JButton();

        editButton = new JButton();
        editButton.setFocusPainted( false );
        editButton.addActionListener( this );

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer( this );
        columnModel.getColumn(column).setCellEditor( this );
    }

    @Override
    public Object getCellEditorValue() {
         return text;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        fireEditingStopped();

        if(text.equals("connect")){
            System.out.println("conn");
        }else if(text.equals("disconnect")){
            System.out.println("disc");
        }
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean selected, int row,
            int column) {
        if(row == showRow){
         text = (value == null) ? "" : value.toString();
            editButton.setText( text );
            return editButton;
        }else{
            return null;
        }
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean hasFocus,
            int row, int column) {
        if (hasFocus) {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        } else if (selected) {
            renderButton.setForeground(table.getSelectionForeground());
             renderButton.setBackground(table.getSelectionBackground());
        } else {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        }

        renderButton.setText((value == null) ? "" : value.toString());
        if(row == showRow) {
            return renderButton;
        } else {
            return null;
        }
    }

}

主要方法

    public static void main(String[] args) {
        ConnectionPanel con = new ConnectionPanel();
        con.setVisible(true);
    }
}

问题

当我使用 "new ButtonColumn(myTable, column, row)" 创建新按钮时,我对不止一行执行此操作,它只显示我在 table 中为每一列创建的最后一个按钮。我真的不明白为什么它会这样。我猜 "ButtonColumn"-class 有问题? 有没有办法只为某些行创建按钮,或者 f.e。直接从 TableModel 创建它们?

你的做法完全错误。 无论如何,您提到的问题的根本原因是: 当您创建 ButtonColumn 实例时,它将成为该列的单元格渲染器和编辑器。 当你执行时,

 new ButtonColumn(licenseTable, 2, 2);
 new ButtonColumn(licenseTable, 2, 3);

现在第 2 列单元格渲染器是 ButtonColumn(licenseTable, 2, 3),对于第 3 行以外的任何行,它将 return 为空。因此您将仅在第 3 行的第 2 列看到按钮。

其他问题:

  1. 编辑器和渲染器不要使用同一个实例,这可能会导致一些绘画问题

  2. 单元格渲染器是一个旨在提供基于行、列、对象的组件。所以你的渲染器可以评估这些值,然后它可以决定它应该 return 一个按钮还是一个空标签。

这里是 mcve 最基础的内容:

public class ButtonTableTest {

    public static void main(String[] args) {
        final Random random = new Random();
        DefaultTableModel tableModel = new DefaultTableModel(20, 7) {
            @Override
            public Class<?> getColumnClass(int arg0) {
              // provide the default renderer and editor of String for empty cells
                return String.class; 
            }

            @Override
            public boolean isCellEditable(int row, int column) {
               // do not request the editor for empty cells
                return !"".equals(getValueAt(row, column));
            }

            @Override
            public Object getValueAt(int row, int column) {
                // some random table content
                if (null == super.getValueAt(row, column)) {
                    int nextInt = random.nextInt(10);
                    if (nextInt > 5)
                        super.setValueAt(String.format("cell %dx%d", row, column), row, column);
                    else
                        super.setValueAt("", row, column);
                }
                return super.getValueAt(row, column);
            }

            @Override
            public void setValueAt(Object arg0, int arg1, int arg2) {
                // prevent update to NULL
            }

        };

        JTable jTable = new JTable(tableModel);
        jTable.setPreferredSize(new Dimension(800, 350));
        final JButton jButton = new JButton();

        jTable.setDefaultRenderer(String.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected,
                        hasFocus, row, column);
                if ("".equals(value)) {
                    // default renderer for empty cells
                    return tableCellRendererComponent;
                } else {
                    jButton.setAction(createSameActionForEditorAndRenderer(table, value));
                    return jButton;
                }
            }
        });
        jTable.setDefaultEditor(String.class, new DefaultCellEditor(new JCheckBox()) { // JCheckBox is closest to a button...

            @Override
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
                    int column) {
                Component tableCellEditorComponent = super.getTableCellEditorComponent(table, value, isSelected, row,
                        column);
                jButton.setAction(createSameActionForEditorAndRenderer(jTable, value));
                return jButton;
            }

        });
        JOptionPane.showMessageDialog(null, jTable);
    }

    private static AbstractAction createSameActionForEditorAndRenderer(JTable table, Object value) {
        return new AbstractAction((String) value) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(table, String.format("clicked on %s",value));
                });
                table.getCellEditor().stopCellEditing();
                table.repaint();
            }
        };
    }
}

When I click into a cell, it often shows the wrong value. Sometimes its the value of another cell from the same row or from a cell that has been previously clicked. I can't figure out why it does that?

这是因为我对渲染器和编辑器使用相同的 JButton 实例。

这是修复它的更改:

        //final JButton jButton = new JButton();

        jTable.setDefaultRenderer(String.class, new DefaultTableCellRenderer() {
           private final JButton jButton = new JButton();
        // rest of renderer

        jTable.setDefaultEditor(String.class, new DefaultCellEditor(new JCheckBox()) { // JCheckBox is closest to a button...
           private final JButton jButton = new JButton();
        // rest of editor

当你打电话时

TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(column).setCellRenderer(this);
columnModel.getColumn(column).setCellEditor(this);

ButtonColumn 的构造函数中,您为列设置了 CellRendererCellEditor。对此的最后一次调用获胜并覆盖该列的 CellRendererCellEditor 的旧设置。

问题不是五分钟的问题。我会创建一个可以容纳 ButtonColumn 的容器,然后可以决定从 ButtonColumn 到 render/edit,但这非常棘手。 可以在下面找到解决渲染问题的快速尝试:

新建内Class行列

A class 用于组合行和列以将其关联到 Map.

static class RowColumn {
    final int row;
    final int column;

    RowColumn(int theColumn, int theRow) {
        this.column = theColumn;
        this.row = theRow;
    }

    public int getRow() {
        return row;
    }

    public int getColumn() {
        return column;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + column;
        result = prime * result + row;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RowColumn other = (RowColumn) obj;
        if (column != other.column)
            return false;
        if (row != other.row)
            return false;
        return true;
    }


}

新建内部 Class ButtonColumnContainer

可容纳 ButtonColumn 的容器。

static class ButtonColumnContainer implements TableCellRenderer {
    Map<RowColumn, ButtonColumn> mapIntToColumn = new HashMap<>();

    ButtonColumn createButtonColumn(JTable table, int column, int row) {

        RowColumn rc = new RowColumn(column, row);
        ButtonColumn buttonColumn = new ButtonColumn(column, row);
        mapIntToColumn.put(rc, buttonColumn);

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer(this);
        // columnModel.getColumn(column).setCellEditor(this);

        return buttonColumn;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean hasFocus,
            int row, int column) {
        ButtonColumn buttonColumn = getButtonColumn(column, row);

        if (buttonColumn != null) {
            JButton renderButton = buttonColumn.getRenderButton();
            if (hasFocus) {
                renderButton.setForeground(table.getForeground());
                renderButton.setBackground(UIManager.getColor("Button.background"));
            } else if (selected) {
                renderButton.setForeground(table.getSelectionForeground());
                renderButton.setBackground(table.getSelectionBackground());
            } else {
                renderButton.setForeground(table.getForeground());
                renderButton.setBackground(UIManager.getColor("Button.background"));
            }

            renderButton.setText((value == null) ? "" : value.toString());
            return renderButton;
        } else {
            return null;
        }
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean selected, int row,
            int column) {
        ButtonColumn buttonColumn = getButtonColumn(column, row);

        if (buttonColumn != null) {
            JButton editButton = buttonColumn.getEditButton();
            String text = (value == null) ? "" : value.toString();
            editButton.setText(text);
            return editButton;
        } else {
            return null;
        }

    }

    private ButtonColumn getButtonColumn(int column, int row) {
        RowColumn rowColumn = new RowColumn(column, row);
        return mapIntToColumn.get(rowColumn);
    }

}

改编内部class ButtonColumn

原来的class已经为JButton添加了getter和setter editButtonrenderButton

static class ButtonColumn extends AbstractCellEditor implements ActionListener {

    final JButton editButton;
    final JButton renderButton;
    String text;
    int showRow;

    public ButtonColumn(int column, int showRow) {
        super();
        this.showRow = showRow;
        renderButton = new JButton();

        editButton = new JButton();
        editButton.setFocusPainted(false);
        editButton.addActionListener(this);

    }

    @Override
    public Object getCellEditorValue() {
        return text;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        fireEditingStopped();

        if (text.equals("connect")) {
            System.out.println("conn");
        } else if (text.equals("disconnect")) {
            System.out.println("disc");
        }
    }

    public JButton getEditButton() {
        return editButton;
    }

    public JButton getRenderButton() {
        return renderButton;
    }



}

而不是对 ButtonColumn

的构造函数的初始调用
ButtonColumnContainer container = new ButtonColumnContainer();
container.createButtonColumn(licenseTable, 2, 0);
container.createButtonColumn(licenseTable, 3, 0);
container.createButtonColumn(licenseTable, 2, 2);
container.createButtonColumn(licenseTable, 3, 2);
container.createButtonColumn(licenseTable, 4, 2);

请注意,此代码无法编辑任何内容,但它至少应该解决渲染问题。