Question

I have a method that returns a DefaultTableModel populated by a database. What I wanted to do is add boolean check boxes to each records returned by adding a new boolean column to the returned DefaultTableModel instance. The user should be able to only click/unclick these checkboxes (Multiple selection should be allowed) to manipulate some map objects I have in the GUI. Other columns should be un-editable. Any ideas on how to achieve this? So far I have gone up to the following point, I have extended TableCellRenderer as follows

public class UGIS_BooleanTableCellRenderer extends JCheckBox implements TableCellRenderer {

          public UGIS_BooleanTableCellRenderer() {
            setHorizontalAlignment(JLabel.CENTER);
          }

      @Override
      public Component getTableCellRendererComponent(JTable table, Object value,
          boolean isSelected, boolean hasFocus, int row, int column) {
        if (isSelected) {
          setForeground(table.getSelectionForeground());
          super.setBackground(table.getSelectionBackground());
          setBackground(table.getSelectionBackground());
        } else {
          setForeground(table.getForeground());
          setBackground(table.getBackground());
        }
        setSelected((value != null && ((Boolean) value).booleanValue()));
        return this;
      }       
}

I can override isCellEditable method also.

DefaultTableModel dm = new DefaultTableModel() {
                @Override
                public boolean isCellEditable(int row, int column) {
                    return column == 3;
                }
            };

But how do I make the DefaultTableModel returned by the method to be compatible with my overrided dm instance? Any help on this would be greatly appreciated.

Was it helpful?

Solution

You can use CheckBox column without writing custom renderer/editor, just overriding getColumnClass() method of TableModel. Here is simple example for your with CheckBox column:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Example extends JFrame {

    public static void main(String... s){
        new Example();
    }

    public Example(){
        DefaultTableModel model = new DefaultTableModel(4,4) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 3;
            }

            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if(columnIndex == 3){
                    return Boolean.class;
                }
                return super.getColumnClass(columnIndex);
            }
        };

        JTable t = new JTable(model);
        add(new JScrollPane(t));

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top