tags:

views:

698

answers:

2

Hi,

I was looking for an answer for a previous question and had an ingenious idea to overcome a limit on JTable. I need the editor to be different on a row by row basis, whereas JTable can only handle a single editor for each column.

So my idea is to use a MouseListener to check the row and column on the JTable and set new editor each time.

But, calling setCellEditor() a second time do not have any effect. The editor remains to be the first one that was set. So how can I make "setCellEditor" work a second time for the same column?

Here's the code in MouseListener.

public void mouseClicked(MouseEvent e) {
    int cols = resultTable.columnAtPoint(new Point(e.getX(), e.getY()));
    int rows = resultTable.rowAtPoint(new Point(e.getX(), e.getY()));
    StorageObject item = (StorageObject) resultTable.getModel().getValueAt(rows, cols);
    TableColumn col = resultTable.getColumnModel().getColumn(cols);
    col.setCellEditor(new MyComboBoxEditor(item.list));
}
+1  A: 

My theory is that when all the mouse listeners registered to the Table/TableCell are invoked, the ones installed to the API classes by default will be invoked first, before your mouse listener. This means the event causing the editor to be fetched will occur before you set it to a different one. Kind of like a race condition, only it's actually defined somewhere in the API source code... That's my naive theory and I can already see some holes in it, so on to my solution:

Override JTable.getCellEditor(int row, int col). This allows you to return whatever editor you want for any cell.

Cogsy
+2  A: 

I'm not sure why your code isn't working (it's been a while since I've done Swing), but why don't you just override

public TableCellEditor getCellEditor(int row, int column)

On your JTable? Maintain a map of the combo boxes you want to use for each row and in your overriden method return the correct one.

MrWiggles
yep. this is how you handle multiple editor types for a single column.
Dave Ray