Technically, the reason boils down to an incorrect event (that you manually created in your action). Apart from the (minor) incorrect source, it's the path argument that's wrong: There are two constructors for a TreeEvent which you mixed up
// one taking a TreePath
public TreeModelEvent(Object source, TreePath path, int[] childIndices,
Object[] children)
// the other taking an array of nodes to the root
public TreeModelEvent(Object source, Object[] path, int[] childIndices,
Object[] children)
// mixture (**WRONG**)
TreeModelEvent event = new TreeModelEvent(this,
// this is an array with the path as single element
new Object[] {rootNew.getPathForRow(3)}, // harcoding because i know i am deleting from dept2
new int[]{1}, //hardcoding as i am removing emp4
new Object[] {emp4});
// technically correct (but **don't** - TreeModelSupport does it for you :-)
TreeModelEvent event = new TreeModelEvent(this,
// this is an array with the path as single element
rootNew.getPathForRow(3), // harcoding because i know i am deleting from dept2
new int[]{1}, //hardcoding as i am removing emp4
new Object[] {emp4});
The real issue is the manual firing under the feet of the model: it's model's inherent responsibility to notify its listeners, so best provide it with api to remove an employee. Even then don't create the event manually which can be done incorrectly easily, that's why SwingX has TreeModelSupport to ease the pain.
// public api in your custom model
public void removeEmployee(Departement dept, Employee emp) {
TreePath path = new TreePath(new Object[] {depList, dept});
int index = dept.empList.indexOf(emp);
dept.empList.remove(emp);
modelSupport.fireChildRemoved(path, index, emp);
}
// its usage in application code
TestModel model = (TestModel) rootTree.getModel();
model.removeEmployee(dept2, emp4);
Unrelated to the notification issue, don't ever return view from model methods, the correct getValueAt would be something like
@Override
public Object getValueAt(Object arg0, int arg1) {
if (arg0 instanceof Employee) {
Employee emp = (Employee) arg0;
return emp.getName();
} else if (arg0 instanceof Departement) {
Departement dept = (Departement) arg0;
return dept.getName();
}
return null;
}