Search code examples
javaswingtablecelleditorabstracttablemodel

AbstractTableModel and cell editor


The example i have found: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm show how to create a JTable with specified column (button). It works properly, but the my problem is, that i need to use AbstractTableModel instead of DefaultTableModel (as at the example shows).

So i created my own TableModel, which extends AbstractTableModel:

public class TableModel extends AbstractTableModel { //..
}

and replaced:

 DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][] { { "button 1", "foo" },
    { "button 2", "bar" } }, new Object[] { "Button", "String" });

JTable table = new JTable(dm);

for:

JTable table = new JTable(new TableModel());

And then nothing happens, when i will click button at some row. Any suggestions?


Solution

  • Make sure you override AbstractTableModel.isCellEditable method to return true for the column with the button otherwise the editor will not be triggered. This method by default returns false.

    Also, make sure you override getColumnName() to return proper name since the sample that you linked tries to find a column with name "Button" to setup the editor.

    You may find a Table Button Column implementation by @camickr useful.

    This demo model works OK with the editor and the renderer from the linked sample:

    public class DemoTableModel extends AbstractTableModel {
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return (columnIndex == 0);
        }
    
        @Override
        public int getRowCount() {
            return 2;
        }
    
        @Override
        public int getColumnCount() {
            return 2;
        }
    
        @Override
        public String getColumnName(int columnIndex) {
            switch (columnIndex) {
            case 0:
                return "Button";
            case 1:
                return "Value";
            }
            return null;
        }
    
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
            case 0:
                return "Button";
            case 1:
                return "Value";
            }
            return null;
        }
    }