TreeCellEditor 在编辑单元格后执行操作
TreeCellEditor perform Action after cell was edited
我想在 CellEditor 消失后执行一个操作。之后调用哪个方法,从哪里开始?
您必须通过将 CellEditorListener
添加到树
来收听 JTree
的 CellEditor
tree.getCellEditor().addCellEditorListener(new CellEditorListener() {
@Override
public void editingStopped(ChangeEvent e) {
System.out.println(((DefaultCellEditor)e.getSource()).getCellEditorValue());
}
@Override
public void editingCanceled(ChangeEvent e) {
System.out.println(((DefaultCellEditor)e.getSource()).getCellEditorValue());
}
});
完整示例
JFrame frame = new JFrame();
//Mock data
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
for (int i = 1; i < 5; i++) {
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Parent" + i);
for (int j = 1; j < 5; j++) {
parent.add(new DefaultMutableTreeNode("Child" + j));
}
root.add(parent);
}
DefaultTreeModel tmodel = new DefaultTreeModel(root);
JTree tree = new JTree(tmodel);
tree.setEditable(true);//To enable editing
tree.getCellEditor().addCellEditorListener(new CellEditorListener() {
@Override
public void editingStopped(ChangeEvent e) {
//add you code here
System.out.println(((DefaultCellEditor) e.getSource()).getCellEditorValue());
}
@Override
public void editingCanceled(ChangeEvent e) {
//add you code here too
System.out.println(((DefaultCellEditor) e.getSource()).getCellEditorValue());
}
});
frame.add(new JScrollPane(tree));
frame.setTitle("Tree Editor Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
我想在 CellEditor 消失后执行一个操作。之后调用哪个方法,从哪里开始?
您必须通过将 CellEditorListener
添加到树
JTree
的 CellEditor
tree.getCellEditor().addCellEditorListener(new CellEditorListener() {
@Override
public void editingStopped(ChangeEvent e) {
System.out.println(((DefaultCellEditor)e.getSource()).getCellEditorValue());
}
@Override
public void editingCanceled(ChangeEvent e) {
System.out.println(((DefaultCellEditor)e.getSource()).getCellEditorValue());
}
});
完整示例
JFrame frame = new JFrame();
//Mock data
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
for (int i = 1; i < 5; i++) {
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Parent" + i);
for (int j = 1; j < 5; j++) {
parent.add(new DefaultMutableTreeNode("Child" + j));
}
root.add(parent);
}
DefaultTreeModel tmodel = new DefaultTreeModel(root);
JTree tree = new JTree(tmodel);
tree.setEditable(true);//To enable editing
tree.getCellEditor().addCellEditorListener(new CellEditorListener() {
@Override
public void editingStopped(ChangeEvent e) {
//add you code here
System.out.println(((DefaultCellEditor) e.getSource()).getCellEditorValue());
}
@Override
public void editingCanceled(ChangeEvent e) {
//add you code here too
System.out.println(((DefaultCellEditor) e.getSource()).getCellEditorValue());
}
});
frame.add(new JScrollPane(tree));
frame.setTitle("Tree Editor Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);