2

I have JTable which first column is editable as a checkbox. It works correct for single row selection, but I don't have any idea what should I do if I want to check more than one row. There is my class which implements TableCellRenderer:

private class MyTableRenderer extends JCheckBox implements TableCellRenderer{

    private int row;

    public MyTableRenderer() {
    }

    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row, int col) {

        if(isSelected) {
            this.row = table.getSelectedRow();

            if(isSelected()) setSelected(false);
            else setSelected(true);
        }
        return this;
    }
}

and there is a part of class which extends AbstractTableModel:

private class CompanyTable extends AbstractTableModel {

    //...

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {

        if(columnIndex==0) {
            MyTableRenderer renderer = new MyTableRenderer();
            TableColumn tableColumn = new TableColumn();
            tableColumn = table.getColumnModel().getColumn(0);
            tableColumn.setCellRenderer(renderer);
            return null;
        }
        if(columnIndex==1)
            //...
        else
            //...
    }

    @Override
    public String getColumnName(int column) {
        // TODO Auto-generated method stub
        return columnsName[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return super.getColumnClass(columnIndex);
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if(columnIndex == 0) return true;
        return false;
    }

Do you have any idea what should I do?

joamor
  • 31
  • 6
  • Simply create a hidden column containing `true/false` value. And change value of cell of same row when checkbox is checked/unchecked.This link would help you for this: http://stackoverflow.com/questions/20898572/change-background-color-of-row-in-jtable-after-selection – Vighanesh Gursale Feb 21 '15 at 19:03
  • 2
    Not sure why you are creating a custom renderer. JTable supports a checkbox renderer and editor if you store Boolean values in the TableModel for that column and you override the getColumnClass(...) method (which you have done).. – camickr Feb 21 '15 at 22:59
  • 1
    for [example](http://stackoverflow.com/a/4528604/230513). – trashgod Feb 22 '15 at 00:46
  • @trashgod I corrected my code basing on yours and it's working. Thanks :) – joamor Feb 27 '15 at 17:42
  • @joamor: Glad you got it sorted. You can [answer your own question](http://meta.stackoverflow.com/q/17463/163188) or I can close as a duplicate. – trashgod Feb 28 '15 at 03:05
  • @trashgod my code is quite similar to yours so I think that you can close this as a duplicate. I'm sorry I didn't find your example before I answered this question. – joamor Mar 01 '15 at 12:48

0 Answers0