1

I am using DefaultTableModel as follows:

  DefaultTableModel model = new DefaultTableModel (COLUMNS, 0 )
  {
      @Override
      public boolean isCellEditable(int row, int column)
      {
          return (getColumnName(column).equals("Selected"));
      }

      public Class getColumnClass(int columnIndex)
      {
          if(getColumnName(columnIndex).equals("Selected"))
              return Boolean.class;
          return super.getColumnClass(columnIndex);
      }     
  };

Now I want to make only one checkbox selectable in the column "Selected". How can this be done. I have tried following method also but its not working.

 public void fireTableCellUpdated(int row,int column)
 {
     if(getColumnName(column).equals("Selected"))
     {
         for(int i = 0; i<getRowCount() && i!=row;i++)
            setValueAt(Boolean.FALSE, row, column);
     }
 }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
eatSleepCode
  • 4,427
  • 7
  • 44
  • 93
  • 1
    If I understood you correctly you want to implement a radio button functionality? – Michał Tabor Jul 30 '13 at 10:24
  • "its not working" - can you be a little more specific? Does it throw an `Exception`, or some other helpful information? What do you see? – mthmulders Jul 30 '13 at 10:24
  • Can i know what IDE are you using? – Nitesh Verma Jul 30 '13 at 10:24
  • It throws StackOverFlow exception. – eatSleepCode Jul 30 '13 at 10:25
  • @NiteshVerma I am using JDeveloper, but does it make any difference – eatSleepCode Jul 30 '13 at 10:26
  • No, No not at all. Just gathering more facts on that. – Nitesh Verma Jul 30 '13 at 10:27
  • 1
    You get `StackOverFlowException` because `setValueAt()` will result in `fireTableCellUpdated()` being called which calls the former again. – kiheru Jul 30 '13 at 10:32
  • 1
    It probably throws StackOverflow because your fireTableCellUpdated mehtod cascades endlessly. – Jannis Alexakis Jul 30 '13 at 10:32
  • Maybe it wanted you to ask Stack Overflow. – tbodt Jul 30 '13 at 10:32
  • Is there any other method to handle this issue? – eatSleepCode Jul 30 '13 at 10:34
  • please whats goal there is one column??? or row??? that contains JCheckBox, – mKorbel Jul 30 '13 at 10:34
  • for better help soner post an [SSCCE](http://sscce.org/), short, runnable, compilable, just about JFrame, JTable and with hardoded value for TableModel – mKorbel Jul 30 '13 at 10:36
  • @mKorbel I have a JTable with one column as boolean.class, there can be many rows in the table but I want to make only one checkbox selected among all the rows. – eatSleepCode Jul 30 '13 at 10:37
  • @eatSleepCode 1. I have a JTable with one column as boolean.class ---> no idea from code posted, for why hells on this world is required to call fireWhatever for DeafultTableModel, don't do that, prepare (to search here for) an SSCCE, 2. but I want to make only one checkbox selected among all the rows ---> nothing special for JTable based on DefaultTableModel, everything is about to override setValueAt correctly, and by blocking, avoiding (cascaded) endless loop (based on comments here), – mKorbel Jul 30 '13 at 10:44
  • Some alternatives are cited [here](http://stackoverflow.com/a/11173600/230513). – trashgod Jul 30 '13 at 10:49
  • @mKorbel can you please give example code for implementing setValueAt method. – eatSleepCode Jul 30 '13 at 10:54

3 Answers3

1
  • @eatSleepCode wrote @mKorbel can you please give example code for implementing setValueAt method.

  • code for (OP used) DefaultTableModel,

  • for code based on AbstractTableModel is required to hold code ordering for notifier fireTableCellUpdated(rowIndex, columnIndex);, because/otherwise nothing will be repainted in JTables view,

  • there are a few important differencies betweens those two models and its notifiers, and (my view) there isn't reason to bothering with and to use AbstractTableModel for basic stuff (99pct of table models)

enter image description here . . . . enter image description here . . . . enter image description here

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

public class TableRolloverDemo {

    private JFrame frame = new JFrame("TableRolloverDemo");
    private JTable table = new JTable();
    private String[] columnNames = new String[]{"Column"};
    private Object[][] data = new Object[][]{{false}, {false}, {true}, {true},
        {false}, {false}, {true}, {true}, {false}, {false}, {true}, {true}};

    public TableRolloverDemo() {
        final DefaultTableModel model = new DefaultTableModel(data, columnNames) {
            private boolean ImInLoop = false;

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

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

            @Override
            public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
                if (columnIndex == 0) {
                    if (!ImInLoop) {
                        ImInLoop = true;
                        Boolean bol = (Boolean) aValue;
                        super.setValueAt(aValue, rowIndex, columnIndex);
                        for (int i = 0; i < this.getRowCount(); i++) {
                            if (i != rowIndex) {
                                super.setValueAt(!bol, i, columnIndex);
                            }
                        }
                        ImInLoop = false;
                    }
                } else {
                    super.setValueAt(aValue, rowIndex, columnIndex);
                }
            }
        };
        table.setModel(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(table));
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TableRolloverDemo tableRolloverDemo = new TableRolloverDemo();
            }
        });
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    gentle reminder (for the umpteenth time) - answer code should be as SSCCE as question code :-) Rollover effects are nice, but unrelated to the question. – kleopatra Jul 30 '13 at 12:42
0

You get an stack overflow exception because setValueAt() method triggers fireTableCellUpdated() method once again and again.

Instead, try using a table listener which would listen to check box's value change and would set all other check boxes' value to false.

Michał Tabor
  • 2,441
  • 5
  • 23
  • 30
-1

You can create your own custom cell editor that joins all check boxes in a column in a ButtonGroup. here's how:

public class VeryComplicatedCellEditor extends DefaultCellEditor {
    private ArrayList<ButtonGroup> groups;

    public getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        JCheckBox checkBox = new JCheckBox();
        growToSize(column);
        groups.get(column).add(checkBox);
        return checkBox;
    }

    private growToSize(int size) {
        groups.ensureCapacity(size);
        while (groups.size() < size)
            groups.add(new ButtonGroup());
    }
}

There are some complications that come from the fact that we don't know how big the table is, which are mostly taken care of in the growToSize method.

The way this works is by maintaining a list of ButtonGroups, one for each column. The editor component for each cell is added to the button group for its column.

tbodt
  • 16,609
  • 6
  • 58
  • 83
  • That´s interesting. Is it doable? Any examples out there ? – Jannis Alexakis Jul 30 '13 at 10:42
  • plain wrong a) doesn't comply to its contract: _must_ notify listeners when editing is terminated b) creating a new checkbox (and buttongroup) at each call - how's that supposed to solve a problem? c) not configuring the checkbox – kleopatra Jul 30 '13 at 12:36