jButton在jTable中无法点击

时间:2016-11-05 12:32:32

标签: java swing jtable jbutton

我遇到了问题,我无法点击按钮。它们的行为就像它们只是带有按钮设计的文本字段。

我的Main

    tableModStudents = (DefaultTableModel) studentsTable.getModel();
    studentsTable.getColumn(studentsTable.getColumnName(8))
                 .setCellRenderer(new JButtonRenderer());
    studentsTable.getColumn(studentsTable.getColumnName(8))
                 .setCellEditor(new JButtonEditor());

我的CellRenderer

public class JButtonRenderer implements TableCellRenderer {    
    private JButton button = new JButton();

    public Component getTableCellRendererComponent(JTable table,
            Object buttonText, boolean isSelected, boolean hasFocus, 
            int row, int column) {
        table.setShowGrid(true);
        button.setText("Details");
        button.setToolTipText(buttonText.toString());
        return button;
    }
}

我的CellEditor

    public class JButtonEditor extends AbstractCellEditor implements TableCellEditor {

    private JButton button;
    private String txt;

    public JButtonEditor() {
        super();
        button = new JButton();
        button.setOpaque(true);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                System.out.println("Button gedrückt!");
            }
        });
    }

    public Object getCellEditorValue() {
        return null;
    }

    public boolean isCellEditable(EventObject anEvent) {
        return true;
    }

    public boolean shouldSelectCell(EventObject anEvent) {
        return false;
    }

    public boolean stopCellEditing() {
        return super.stopCellEditing();
    }

    public void cancelCellEditing() {
    }

    public void addCellEditorListener(CellEditorListener l) {
    }

    public void removeCellEditorListener(CellEditorListener l) {
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        txt = (value == null) ? "" : value.toString();
        button.setText(txt);
        return button;
    }
}

你能找到问题吗?它让我疯狂......

非常感谢:)

1 个答案:

答案 0 :(得分:1)

查看Table Button Column

它将按钮渲染器和编辑器组合在一个类中。

您需要做的就是在调用按钮时(通过单击它或通过调用其助记符)提供要调用的自定义Action