Tree Component (JTree)
A tree can only have one parent node, and it can have zero or more children. By default, each node can have children, and it can be set to not have children.
Common construction methods:
public JTree() creates a default tree
public JTree(TreeNode root) creates a tree from the root node
public JTree(TreeModel newModel) creates a tree based on the specified tree model
common method | Explain |
---|---|
public boolean isSelectionEmpty() | Check to see if the selected node exists and return true if the selection is currently empty. |
public TreeSelectionModel getSelectionModel() | Get the tree option model that you can use to set the selection mode |
public int getSelectionCount() | Get the number of selected nodes |
public TreePath getSelectionPath() | Gets the path of the node with the smallest index value among the selected nodes |
public TreePath[] getSelectionPaths() | Returns the path of all selected nodes. |
public void setRootVisible(boolean rootVisible) | Determines whether the root node of TreeModel is visible. |
public void setShowsRootHandles(boolean newValue) | Sets the value of the showsRootHandles property, which specifies whether node handles should be displayed. |
public TreeCellRenderer getCellRenderer() | Returns the current TreeCellRenderer that is rendering each cell. |
public void setRowHeight(int rowHeight) | Set the height of each cell in pixels.If the specified value is less than or equal to zero, the current cell renderer is queried to get the height of each row. |
public void setFont(Font font) | Set the font for this component. |
public void setSelectionPath(TreePath path) | Select the node identified by the specified path. |
public boolean isVisible(TreePath path) | Returns true if the value of the path identifier is currently viewable, meaning that the path is either the root path or all its parent paths are expanded.Otherwise, this method returns false.Simply put, is there any expanded display of this node |
public void makeVisible(TreePath path) | Ensure that the node identified by the path is currently viewable.Is to force expansion to show |
public void setModel(TreeModel newModel) | Set the TreeModel that will provide the data. |
DefaultMutableTreeNode
DefaultMutableTreeNode implements the TreeNode tree node interface, which is used to create the nodes of the tree.
Common construction methods:
public DefaultMutableTreeNode() creates a tree node with no parent and no child nodes, but it allows child nodes.
public DefaultMutableTreeNode(Object userObject) creates a node with a specified tag.
public DefaultMutableTreeNode(Object userObject,boolean allowsChildren) creates a node with the specified tag and specifies whether child nodes are allowed.
common method | Explain |
---|---|
public void add(MutableTreeNode newChild) | Add a child node for this node |
public Enumeration preorderEnumeration() | Returns the enumerated object traversed in preceding order |
public Enumeration postorderEnumeration() | Returns enumerated objects traversed in sequential order |
public Enumeration breadthFirstEnumeration() | Returns enumerated objects traversed in width first |
public Enumeration depthFirstEnumeration() | Returns enumerated objects traversed depth first |
public Enumeration children() | Returns an enumerated object that contains only the child nodes of this node |
public int getLevel() | Gets the level value of the node relative to the root node, such as the level value of the child node of the root node being 1 |
public int getDepth() | Gets the depth of the tree with this node as its root node, which is 0 if the node has no children |
public TreeNode getParent() | Get the parent node object of this node |
public int getChildCount() | Returns the number of child nodes of this node. |
public TreeNode getFirstChild() | Returns the first child node of this node.If this node has no children, a NoSuchElementException is thrown. |
public int getSiblingCount() | Returns the number of siblings of this node. |
public DefaultMutableTreeNode getNextSibling() | The last sibling node to get this node |
public DefaultMutableTreeNode getPreviousSibling() | Get the previous sibling node of this node |
public TreeNode[] getPath() | Returns the path from the root to this node.The last element in the path is this node. |
public boolean isRoot() | Returns true if this node is the root of a tree.Root is the only node in the tree whose parent node is null; each tree has only one root. |
public boolean isLeaf() | Returns true if this node has no children.To distinguish between a node that has no children and a node that cannot have children |
public void setUserObject(Object userObject) | Set the user object of this node to userObject.That is, modify the user label |
public Object getUserObject() | Returns the user object for this node.Get the user label |
DefaultTreeModel
DefaultTreeModel implements the TreeModel interface.
Common construction methods:
The public DefaultTreeModel(TreeNode root) creates a tree model that uses the default way to determine whether a node is a leaf node or not.
The public DefaultTreeModel(TreeNode root,boolean asksAllowsChildren) creates a tree model that determines whether a node is a leaf node in a specified way.
Note: There are two ways to determine whether a node is a leaf node or not: 1. Default: if no child node exists for a node, it is a leaf node.2. According to whether a node allows children, as long as no children are allowed to be leaf nodes, if children are allowed, they are not leaf nodes even if they do not contain any children.When asksAllowsChildren is true, the second judgment is used.
common method | Explain |
---|---|
public void insertNodeInto(MutableTreeNode newChild,MutableTreeNode parent,int index) | Call it to insert newChild at the index position in the child node of the parent node.(Add a tree node).NewChild: add a new node object; parent: the parent node object to which the newly added node belongs, which must be a node in the tree model; index: the index position of the newly added node in its parent node, with index value starting from 0 |
public void nodeChanged(TreeNode node) | This method is called after changing the node's representation in the tree.(Modify Node) |
public void removeNodeFromParent(MutableTreeNode node) | Notifies it to remove a node from its parent node. |
Code example: public class ExampleFrame_01 extends JFrame { private static final long serialVersionUID = 1L; public static void main(String args[]) { ExampleFrame_01 frame = new ExampleFrame_01(); frame.setVisible(true); } public ExampleFrame_01() { super(); setTitle("Simple Tree"); setBounds(100, 100, 500, 375); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create Root Node DefaultMutableTreeNode root = new DefaultMutableTreeNode("root node"); // Create a Level 1 Node DefaultMutableTreeNode nodeFirst = new DefaultMutableTreeNode( "First-level child nodes A"); root.add(nodeFirst);// Add a first-level node to the root node DefaultMutableTreeNode nodeSecond = new DefaultMutableTreeNode( "Secondary Child Node", false);// Create secondary nodes that do not allow child nodes nodeFirst.add(nodeSecond);// Add a secondary node to a primary node root.add(new DefaultMutableTreeNode("First-level child nodes B"));// Create a Level 1 Node JTree treeRoot = new JTree(root);// Create a tree directly from the root node getContentPane().add(treeRoot, BorderLayout.WEST); // Use root node to create tree model, using default judgment DefaultTreeModel treeModelDefault = new DefaultTreeModel(root); // Creating a tree using a tree model JTree treeDefault = new JTree(treeModelDefault); getContentPane().add(treeDefault, BorderLayout.CENTER); // Create a tree model from the root node and use a non-default judgment DefaultTreeModel treeModelPointed = new DefaultTreeModel(root, true); JTree treePointed = new JTree(treeModelPointed);// Creating a tree using a tree model getContentPane().add(treePointed, BorderLayout.EAST); } }
TreeSelectionModel
Tree selection mode can be set through the TreeSelectionModel interface
common method | Explain |
---|---|
void setSelectionMode(int mode) | Set the selection model, which must be one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION, or DISCONTIGUOUS_TREE_SELECTION |
Select mode static constants:
static const | constant value | Explain |
---|---|---|
SINGLE_TREE_SELECTION | 1 | Only one is allowed |
CONTIGUOUS_TREE_SELECTION | 2 | Allow multiple consecutive selections |
DISCONTIGUOUS_TREE_SELECTION | 4 | Allows any number of selections, which is the default mode for trees |
TreeSelectionListener interface and TreeSelectionEvent
TreeSelectionListener interface:
Tree component registration listener: addTreeSelectionListener
Void valueChanged (TreeSelectionEvent): Triggered when a node is selected or cancelled
(Tree)e.getSource() is the tree object of the selected node.
TreePath class
TreePath represents the path of the tree node.TreePath is an array of Objects provided by TreeModel.Sort the elements of the array so that the root is always the first element of the array (index is 0).
common method | Explain |
---|---|
public Object[] getPath() | Returns an ordered array of elements for this TreePath.The first element is the root, which is the object that returns all the nodes in the path as an Object array in the order from the root node to the child node. |
public Object getLastPathComponent() | Returns the last element of this path.That is, the object of the last node of this path |
public TreePath getParentPath() | Return to your parent's TreePath.The return value of null indicates that this is the root node. |
public TreePath pathByAddingChild(Object child) | Gets the path after adding the specified node to the path |
public int getPathCount() | Number of nodes in the return path |
public Object getPathComponent(int index) | Returns the node object in the path at the specified index position |
Traverse Tree Nodes
1. Pre-order traversal
2. Post-order traversal
3. Width first traversal
4. Depth first traversal
The DefaultMutableTreeNode class provides two sets of relative traversals:
Method | Explain |
---|---|
public Enumeration preorderEnumeration() | Returns the enumerated object traversed in preceding order |
public Enumeration postorderEnumeration() | Returns enumerated objects traversed in sequential order |
public Enumeration breadthFirstEnumeration() | Returns enumerated objects traversed in width first |
public Enumeration depthFirstEnumeration() | Returns enumerated objects traversed depth first |
public Enumeration children() | Returns an enumerated object that contains only the child nodes of this node |
Note: Since post-order traversal and depth-first traversal are the same, the method depthFirstEnumeration() actually calls the method postorderEnumeration().
Enumeration<?> enumeration; // Traverse all tree nodes in preceding order enumeration = root.preorderEnumeration(); while (enumeration.hasMoreElements()) { DefaultMutableTreeNode node; node = (DefaultMutableTreeNode) enumeration.nextElement(); if (!node.isLeaf()) {// Determine whether it is a leaf node // Path to create this node TreePath path = new TreePath(node.getPath()); tree.expandPath(path);// Expand the node if not }
Custom Tree
1. Custom Root Node Effect: By default, the root node of the tree is displayed, but the root node handle is not displayed.This can be set by the following methods in the JTree class:
Method | Explain |
---|---|
public void setRootVisible(boolean rootVisible) | Determines whether the root node of TreeModel is visible. |
public void setShowsRootHandles(boolean newValue) | Sets the value of the showsRootHandles property, which specifies whether node handles should be displayed. |
2. Custom Icons: Node icons can be modified by objects of the DefaultTreeCellRenderer class (implementation class for the TreeCellRenderer interface), which is obtained by the public TreeCellRenderer getCellRenderer() (forced) method of the JTree class, as follows:
Method | Explain |
---|---|
public void setLeafIcon(Icon newIcon) | Sets the icon used to represent the leaf node. |
public void setClosedIcon(Icon newIcon) | Sets the icon used to represent non-leaf nodes that do not have extensions. |
public void setOpenIcon(Icon newIcon) | Sets the icon used to represent the extended non-leaf node. |
3. Custom connection line effect: By default, connection lines are drawn between tree nodes, and the connection lines are drawn by public final void putClientProperty(Object key,Object value).Set the entry parameter key to "JTree.lineStyle".Value is None, which means no connection lines between nodes are drawn; Horizontal, which means drawing horizontal column lines; Angled, which means drawing connection lines between nodes, which is equivalent to the default setting.
4. By default, only the root node of the tree is expanded, and all other child nodes are collapsed.If you want a node of the tree to be expanded at the first run time, you need to pass in the path of the expanded node through the public void expandPath(TreePath path) method.
public class ExampleFrame_04 extends JFrame { private static final long serialVersionUID = 1L; private JTree tree; public static void main(String args[]) { ExampleFrame_04 frame = new ExampleFrame_04(); frame.setVisible(true); } public ExampleFrame_04() { super(); setTitle("Custom Tree"); setBounds(100, 100, 200, 325); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DefaultMutableTreeNode root; root = new DefaultMutableTreeNode("Enterprise Personnel Management System"); DefaultMutableTreeNode nodeFirstA; nodeFirstA = new DefaultMutableTreeNode("personnel management"); nodeFirstA.add(new DefaultMutableTreeNode("Ledger Management")); nodeFirstA.add(new DefaultMutableTreeNode("Attendance management")); nodeFirstA.add(new DefaultMutableTreeNode("Reward and Punishment Management")); nodeFirstA.add(new DefaultMutableTreeNode("Training Management")); root.add(nodeFirstA); DefaultMutableTreeNode nodeFirstB; nodeFirstB = new DefaultMutableTreeNode("Treatment Management"); nodeFirstB.add(new DefaultMutableTreeNode("Ledger management")); nodeFirstB.add(new DefaultMutableTreeNode("Personnel Settings")); nodeFirstB.add(new DefaultMutableTreeNode("Treatment Report")); root.add(nodeFirstB); DefaultMutableTreeNode nodeFirstC; nodeFirstC = new DefaultMutableTreeNode("system maintenance"); nodeFirstC.add(new DefaultMutableTreeNode("Enterprise Architecture")); nodeFirstC.add(new DefaultMutableTreeNode("Basic Data")); nodeFirstC.add(new DefaultMutableTreeNode("System Initialization")); root.add(nodeFirstC); tree = new JTree(root); tree.setRootVisible(false);// Do not display the root node of the tree tree.setRowHeight(20);// The row height of the tree node is 20 pixels tree.setFont(new Font("Song Style", Font.BOLD, 14));// Set the font of the tree node // No connection lines between nodes tree.putClientProperty("JTree.lineStyle", "None"); DefaultTreeCellRenderer treeCellRenderer;// Get the drawing object of the tree node treeCellRenderer = (DefaultTreeCellRenderer) tree .getCellRenderer(); treeCellRenderer.setLeafIcon(null);// Set leaf nodes without icons treeCellRenderer.setClosedIcon(null);// Set node collapse without Icon treeCellRenderer.setOpenIcon(null);// Set the node to expand without icons Enumeration<?> enumeration; // Traverse all tree nodes in preceding order enumeration = root.preorderEnumeration(); while (enumeration.hasMoreElements()) { DefaultMutableTreeNode node; node = (DefaultMutableTreeNode) enumeration.nextElement(); if (!node.isLeaf()) {// Determine whether it is a leaf node // Path to create this node TreePath path = new TreePath(node.getPath()); tree.expandPath(path);// Expand the node if not } } getContentPane().add(tree, BorderLayout.CENTER); } }
Maintain tree model
1. Add a tree node (add a new node to the tree model)
2. Modify the tree node: The nodeChanged(TreeNode node) method in the DefaultTreeModel class is used to notify the tree model that a node has been modified. If the user object of the node is modified, the modified information will not be synchronized to the GUI interface.
3. Delete the tree node: Delete the specified node from the tree model.
Method | Description (method in DefaultTreeModel tree model) |
---|---|
public void insertNodeInto(MutableTreeNode newChild,MutableTreeNode parent,int index) | Call it to insert newChild at the index position in the child node of the parent node.(Add a tree node).NewChild: add a new node object; parent: the parent node object to which the newly added node belongs, which must be a node in the tree model; index: the index position of the newly added node in its parent node, with index value starting from 0 |
public void nodeChanged(TreeNode node) | This method is called after changing the node's representation in the tree.(Modified node) node is the modified node object. |
public void removeNodeFromParent(MutableTreeNode node) | Notifies it to remove a node from its parent node. |
1.Add Node addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode node = new DefaultMutableTreeNode( textField.getText());// Create the node you want to add TreePath selectionPath = tree.getSelectionPath();// Get the selected parent node path DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();// Get the selected parent node treeModel.insertNodeInto(node, parentNode, parentNode .getChildCount());// After inserting a node into all child nodes TreePath path = selectionPath.pathByAddingChild(node);// Get the path to the newly added node if (!tree.isVisible(path)) tree.makeVisible(path);// Make this node visible if it is not visible } }); 2.Modify Node updButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the selected path to modify the node TreePath selectionPath = tree.getSelectionPath(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath .getLastPathComponent();// Get the selected node to modify node.setUserObject(textField.getText());// Modify the user label of a node treeModel.nodeChanged(node);// Notification tree model The node has been modified tree.setSelectionPath(selectionPath);// Select the modified node } }); 3.Delete Node delButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree .getLastSelectedPathComponent();// Get the selected node to delete // Check to see if the node you want to delete is a root node, the root node does not allow deletion if (!node.isRoot()) { DefaultMutableTreeNode nextSelectedNode = node .getNextSibling();// Get the next sibling node to select if (nextSelectedNode == null)// Check for sibling nodes nextSelectedNode = (DefaultMutableTreeNode) node .getParent();// Select its parent if it does not exist treeModel.removeNodeFromParent(node);// Delete Node tree.setSelectionPath(new TreePath(nextSelectedNode .getPath()));// Selected Node } } });
Handle Expanded Node Events
1.TreeWillExpandListener interface and TreeExpansionEvent
2.TreeExpansionListener interface and TreeExpansionEvent
listener interface | Event Name | describe |
---|---|---|
TreeWillExpandListener | TreeExpansionEvent | When a tree node is expanded and collapsed, a TreeExpansionEvent event is issued that can be captured before the tree node is expanded and collapsed by implementing the TreeWillExpandListener interface. |
TreeExpansionListener | TreeExpansionEvent | By implementing the TreeExpansionListener interface, you can capture this event when a tree node expands and collapses |
Monitoring interface method and instructions:
1.TreeWillExpandListener interface:
Can be used to require user permissions to be verified, and tree nodes are not allowed to expand if the user does not have permission to view the child nodes contained in the node.
Method | trigger |
---|---|
void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException | Called whenever a node in the tree is to be expanded. |
void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException | Called whenever a node in the tree is collapsed. |
2.TreeExpansionListener interface:
Method | trigger |
---|---|
void treeExpanded(TreeExpansionEvent event) | Called whenever an item in the tree is expanded. |
void treeCollapsed(TreeExpansionEvent event) | Called whenever an item in the tree is collapsed. |
3.TreeExpansionEvent
common method | Explain |
---|---|
public TreePath getPath() | Returns the path to the value that has been expanded/collapsed. |
Examples are as follows: tree.addTreeWillExpandListener(new TreeWillExpandListener() { // Triggered when the tree node is about to be collapsed public void treeWillCollapse(TreeExpansionEvent e) { TreePath path = e.getPath();// Get the path of the node to be collapsed DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent();// Get the node that will be collapsed System.out.println("Node "" + node + ""Will be folded!"); } // Triggered when the tree node is about to be expanded public void treeWillExpand(TreeExpansionEvent e) { TreePath path = e.getPath();// Get the path of the node to be expanded DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent();// Get the node that will be expanded System.out.println("Node "" + node + ""Will be expanded!"); } }); // Capture events where tree nodes have been expanded or collapsed tree.addTreeExpansionListener(new TreeExpansionListener() { // Triggered when the tree node has collapsed public void treeCollapsed(TreeExpansionEvent e) { TreePath path = e.getPath();// Get the path of a node that has been collapsed DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent();// Get a node that has been collapsed System.out.println("Node "" + node + ""Folded!"); System.out.println(); } // Triggered when the tree node has been expanded public void treeExpanded(TreeExpansionEvent e) { TreePath path = e.getPath();// Get the path of the node that has been expanded DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent();// Get the expanded node System.out.println("Node "" + node + ""Already expanded!"); System.out.println(); } });