import java.awt.BorderLayout;
import java.util.EventObject;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeNode;
public class EditLeafSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Editable Tree");
JTree tree = new JTree();
tree.setEditable(true);
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree
.getCellRenderer();
TreeCellEditor editor = new LeafCellEditor(tree, renderer);
tree.setCellEditor(editor);
JScrollPane scrollPane = new JScrollPane(tree);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
class LeafCellEditor extends DefaultTreeCellEditor {
public LeafCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
super(tree, renderer);
}
public LeafCellEditor(JTree tree, DefaultTreeCellRenderer renderer,
TreeCellEditor editor) {
super(tree, renderer, editor);
}
public boolean isCellEditable(EventObject event) {
boolean returnValue = super.isCellEditable(event);
if (returnValue) {
Object node = tree.getLastSelectedPathComponent();
if ((node != null) && (node instanceof TreeNode)) {
TreeNode treeNode = (TreeNode) node;
returnValue = treeNode.isLeaf();
}
}
return returnValue;
}
}
|