JTable cell value change listener
Which listener can be used to react to the event of JTable cell value chan开发者_开发技巧ge? I tried using TableModelListener but either I got something wrong, or this listener doesn't react on changing the contents of a cell.
I need to act either to changing the content of a cell or to cell losing focus. What is the best way to do this? Thanks.
class extends JTable {
.... (inside contructor)
addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("tableCellEditor".equals(evt.getPropertyName())) {
if (isEditing())
processEditingStarted();
else
processEditingStopped();
}
}
});
... (end constructor)
protected void processEditingStopped() {
System.out.println("save " + editingRow + ":" + editingColumn);
}
protected void processEditingStarted() {
System.out.println("edit " + editingRow + ":" + editingColumn);
if (editRow > -1 && editColumn > -1)
oldValue = (String) model.getValueAt(editRow, editColumn);
}
}
more details here: http://tips4java.wordpress.com/2009/06/07/table-cell-listener/
Easy way to react to values changing is to customize a table model and react to setValueAt()
.
If you're looking to make sure edits "stick" when it loses focus, call this on the table.
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
As mentioned by Bill, it maybe easier to "watch" the model rather than the JTable, I used this and was able to track changes by column and row:
list.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
System.out.println("Column: " + e.getColumn() + " Row: " + e.getFirstRow());
}
});
As mentioned in my comment to their answer, it doesn't detect if a change occured only that the cell was edited. So you'll need to check against the original value somehow. But this saved me messing with my JTable constructor.
精彩评论