jButton not clickable in jTable

被刻印的时光 ゝ 提交于 2020-12-13 03:07:55

问题


I got the problem, that I cannot click on buttons. They behave like they are just textfields with the design of buttons.

my Main:

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

my 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;
    }
}

my 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;
    }
}

Can you find the issue with that? It drives my crazy...

Thanks so much :)


回答1:


Check out Table Button Column.

It combines a button renderer and editor in a single class.

All you need to do is provide the custom Action to be invoked when you invoke the button (either by clicking on it or by invoking its mnemonic).



来源:https://stackoverflow.com/questions/40438290/jbutton-not-clickable-in-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!