tags:

views:

55

answers:

3

Hi,

In my JTable, I have two editable numeric columns. The editor for both columns extends AbstractCellEditor and uses a JFormattedTextField as an the editing component.

The problem is that the format for input depends on the value of another column in the row. If condition X is met, the number of fraction digits should be Y, otherwise they should be Y+2.

I attempted to override the getTableCellEditor(..) method to associate a TableCellEditor per row. See this example. However, since I have two editable columns, sharing a single TableCellEditor object per row gives some very odd results. I don't think this is an appropriate solution.

Any ideas on how to approach this would be much appreciated!

Thank you!

+3  A: 

I don't think you need to associate a TableCellEditor per row.

You only need one , which will access other data by himself. in the getTableCellEditor(), you have access to the table, as well as the coordinates (column, row).

With this, you can ask directly the table for its value at the wanted column, for the current row.

Keep in mind that like renderers, cell editors are "shared". You are indeed asking the same object to provide you the editor component (which is most of the time the TableCellEditor itself, extending a JFormattedTextField, for example). So you don't need to put one per row, the method getTableCellEditor() will be called, with the current column and row indexes, and you will provide the component, with the appropriate format, depending on the condition..

Something like this:

public Component getTableCellEditorComponent(JTable table,
                                             Object value,
                                             boolean isSelected,
                                             int row,
                                             int column)
{
    Object data = table.getValueAt(row, CONDITION_COLUMN);
    if (data is something)
        this.setFormat(FORMAT1);
    else
        this.setFormat(FORMAT2);

    return this;
}
Gnoupi
+2  A: 

You can solve it by creating yet another TableCellEditor which will delegate to either of its two subcontractors: the instances of your current cell editors. You need to register this uber-celleditor with the column and let it delegate whenever it is used by Swing.

Itay
Itay - thank you. This is the approach I used and it works well.
Luhar
+2  A: 

I would override the getCellEditor(...) method of JTable. Then you can return the appropriate editor based on the format of the data.

camickr