首页 > 解决方案 > 无法按下表格单元格中的按钮

问题描述

我正在使用 Java Swing 制作一个带有按钮的表格,我可以使用这些按钮作为基于行的操作。

我正在使用自定义单元格渲染器尝试在表格单元格中渲染多个按钮。我已经设法拼凑出一些可以在视觉上实现我想要但按钮实际上不起作用的东西。它们根本不会触发,也不会对点击或鼠标悬停做出视觉反应。寻找一种让按钮做出反应并实际触发它们的动作的方法。

单元格渲染器类:

public class ButtonsCell extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
    JPanel panel;

    public ButtonsCell() {
        this.updateData(Collections.emptyList());
    }

    private void updateData(List<JButton> buttons) {
        this.panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));


        for(JButton button : buttons) {
            button.setMargin(new Insets(-2, 0, -2, 0));

            this.panel.add(button);
        }
    }

    private void updateData(List<JButton> buttons, boolean isSelected, JTable table) {
        this.updateData(buttons);

        if (isSelected) {
            this.panel.setBackground(table.getSelectionBackground());
        }else{
            this.panel.setBackground(table.getBackground());
        }
    }

    public Component getTableCellEditorComponent(JTable table, Object value,
                                                 boolean isSelected, int row, int column) {
        this.updateData((List<JButton>)value, isSelected, table);
        return panel;
    }

    public Object getCellEditorValue() {
        return null;
    }

    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus, int row, int column) {
        this.updateData((List<JButton>)value, isSelected, table);
        return panel;
    }
}

从视觉上看,这会产生:

在此处输入图像描述

标签: javaswingjtablejbutton

解决方案


推荐阅读