I am creating a app in Java. I need to provide additional behavior when editing of a cell in a JTable. So ideally this will happen when the cell loses focus after editing. Depending upon some post processing I might reset the value of the cell. I tried using a a Cell Editor but it is not giving me the desired behavior.
In the default JTable only when I Double click a cell it becomes editable. But in my implementation of CellEditor the cell becomes editable as soon as it comes into focus.
Here is the code for the My custom CellEditor,
public class ParameterDefinitionEditor
extends AbstractCellEditor
implements TableCellEditor{
private JTable table;
private DefaultTableModel defaultTableModel;
public ParameterDefinitionEditor(DefaultTableModel defaultTableModel,
JTable table) {
super();
this.table = table;
this.defaultTableModel = defaultTableModel;
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setCellEditor(this);
}
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
if (isSelected) {
// Do some processing.
}
((JTextField)component).setText((String)value);
// Return the configured component
return component;
}
public Object getCellEditorValue() {
return ((JTextField)component).getText();
}
}
Any help will be appreciated. Thanks.
i achieved that type of behaviour by overriding stopCellEditing ( i use a custom implementation of AbstractCellEditor )
You can do this right in the cell editor if you desire by overriding the stopCellEditing() method.
Extend the DefaultCellEditor. This is controlled by the setClickCountToStart() method.
I agree with the other suggestion that you should probably be adding the TableModelListener to the TableModel. Although depending on your requirement you may want to consider using the Table Cell Listener.
I don't think by providing custom cell editor serves your purpose.
If you want to do some processing based on user actions then your table model should have
a set of listeners (that implement TableModelListener) and your logic should be put
in the "tableChanged" method.
Check this section on Swing tutorial as well:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html