2

I use the following code to generate a table with three columns and three rows, the first column contains checkboxes, and the second column just contains the word : row i, where i corresponds to the row number.

private void loadTable {
       int rowCount  = 3;
     Boolean [] boolArray  = new Boolean[3];

     for(int y=0;y<3;y++)
         boolArray[y]=false;

     int columnCount = 2;
     Object data[] = new Object [rowCount];
      for(int y=1;y<=3;y++)
         data[y-1]="row "+y;

     mainModel = new DefaultTableModel();
     mainModel.addColumn("", boolArray);
     mainModel.addColumn("", data);
       jScrollPane1.getViewport().add(tableOne, null);
     aTableClass.setModel(mainModel);

}     




class ATableClass extends JTable {
              public Class getColumnClass(int column) {
                try {
                  if (column == 0) {
                    return Class.forName("java.lang.Boolean");
                  }
                  return Class.forName("java.lang.Object");
                }
                catch (ClassNotFoundException ex) {
                  ex.printStackTrace();
                  return null;
                }
              }
            }

How can I add actionlisteners to the generated checkboxes inside this table ?

Heisenbug
  • 38,762
  • 28
  • 132
  • 190
shaw
  • 215
  • 2
  • 5
  • 9

1 Answers1

3

You have to define your custom cell table renderers and editors, and add the action listener to the rendered components . Have a look at this thread. This example has been very helpful to me.

In a few word you have to:

  1. implement somewhere TableCellRenderer interface (define how your column will be rendered)
  2. implement somewhere TableCellEditor interface (define how your column will be edited)
  3. adding to your JTable the desired renderer and editor (setDefaultRenderer,setDefaultEditor)
Community
  • 1
  • 1
Heisenbug
  • 38,762
  • 28
  • 132
  • 190