Java Tutorial/Swing/JTree — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:33, 31 мая 2010
Содержание
- 1 Adding children DefaultMutableTreeNode to its parent
- 2 Adding editable nodes to JTree
- 3 All rows will be given 15 pixels of height
- 4 Changing the icons of a tree: UIManager.put(Tree.openIcon, new ImageIcon(yourFile.gif));
- 5 Create JTree from Vector
- 6 Creating a JTree
- 7 Creating a JTree Component
- 8 Creating DefaultTreeCellEditor from its Default Tree Renderer
- 9 Drag and drop of a group of files into a tree
- 10 Dynamic Tree
- 11 Expansion and Collapse Events in a JTree are fired before a node is expanded or collapsed can be vetoed, thereby preventing the operation.
- 12 Finding a Node in a JTree Component
- 13 Find the path regardless of visibility that matches the specified sequence of names
- 14 Have a popup attached to a JTree
- 15 Have the row height for each row computed individually
- 16 JTree.DynamicUtilTreeNode Class
- 17 JTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION)
- 18 JTree.lineStyle client property
- 19 JTree Look and Feel
- 20 Listening for Expansion and Collapse Events in a JTree Component
- 21 Preventing Expansion or Collapse of a Node in a JTree: override JTree.setExpandedState()
- 22 Preventing the Expansion or Collapse of a Node in a JTree Component
- 23 Produce horizontal lines between level-one nodes
- 24 Scrolling Trees: public void scrollPathToVisible(TreePath path) and public void scrollRowToVisible(int row)
- 25 Search backward from last visible row looking for any visible node whose name starts with prefix.
- 26 Setting the Row Height of a JTree
- 27 To find out when a tree node has been expanded or collapsed
- 28 Traveling to all the nodes
- 29 Traverse all expanded nodes in tree
- 30 Traversing Trees
- 31 Tree Will Expand Listener
- 32 Using Boolean value cell renderer to display boolean and non-boolean values
- 33 Using Vector to store JTree values
- 34 Visiting All the Nodes in a JTree Component
- 35 Working with the Nodes of the Tree
Adding children DefaultMutableTreeNode to its parent
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class DefaultMutableTreeNodeAddingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.add(mercury);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
root.add(venus);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("Mars");
root.add(mars);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Adding editable nodes to JTree
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class Main extends JFrame {
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("J");
DefaultTreeModel model = new DefaultTreeModel(rootNode);
JTree m_tree = new JTree(model);
JButton addButton;
public Main() {
DefaultMutableTreeNode forums = new DefaultMutableTreeNode("F");
forums.add(new DefaultMutableTreeNode("T"));
DefaultMutableTreeNode articles = new DefaultMutableTreeNode("A");
articles.add(new DefaultMutableTreeNode("1"));
DefaultMutableTreeNode examples = new DefaultMutableTreeNode("E");
examples.add(new DefaultMutableTreeNode("2"));
rootNode.add(forums);
rootNode.add(articles);
rootNode.add(examples);
m_tree.setEditable(true);
m_tree.setSelectionRow(0);
JScrollPane scrollPane = new JScrollPane(m_tree);
getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
addButton = new JButton("Add Node");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
DefaultMutableTreeNode selNode = (DefaultMutableTreeNode) m_tree
.getLastSelectedPathComponent();
if (selNode != null) {
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node");
model.insertNodeInto(newNode, selNode, selNode.getChildCount());
TreeNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
m_tree.scrollPathToVisible(path);
m_tree.setSelectionPath(path);
m_tree.startEditingAtPath(path);
}
}
});
panel.add(addButton);
getContentPane().add(panel, BorderLayout.SOUTH);
setSize(300, 400);
setVisible(true);
}
public static void main(String[] arg) {
new Main();
}
}
All rows will be given 15 pixels of height
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
public class TreeRowHeight15 {
public static void main(String[] argv) {
JTree tree = new JTree();
tree.setRowHeight(15);
JFrame frame = new JFrame("Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(tree));
frame.setSize(380, 320);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Changing the icons of a tree: UIManager.put(Tree.openIcon, new ImageIcon(yourFile.gif));
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
class TreeNodeVector<E> extends Vector<E> {
String name;
TreeNodeVector(String name) {
this.name = name;
}
TreeNodeVector(String name, E elements[]) {
this.name = name;
for (int i = 0, n = elements.length; i < n; i++) {
add(elements[i]);
}
}
public String toString() {
return "[" + name + "]";
}
}
public class ChangingTreeOpenIcon {
public static void main(final String args[]) {
UIManager.put("Tree.openIcon", new ImageIcon("yourFile.gif"));
JFrame frame = new JFrame("JTreeSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v1 = new TreeNodeVector<String>("Two", new String[] { "Mercury", "Venus",
"Mars" });
Vector<Object> v2 = new TreeNodeVector<Object>("Three");
v2.add(System.getProperties());
v2.add(v1);
Object rootNodes[] = {v1, v2 };
Vector<Object> rootVector = new TreeNodeVector<Object>("Root", rootNodes);
JTree tree = new JTree(rootVector);
frame.add(new JScrollPane(tree), BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Create JTree from Vector
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
public class SimpleTreeTest extends JFrame {
public static void main(String[] args) {
SimpleTreeTest stt = new SimpleTreeTest();
stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stt.setSize(250, 250);
stt.setVisible(true);
}
public SimpleTreeTest() {
Object[] genealogy = { "A", "B", "C", "D", "E", "F" };
java.util.Vector v = new java.util.Vector() {
public String toString() {
return "DD";
}
};
v.addElement("1");
v.addElement("2");
v.addElement("3");
v.addElement("4");
genealogy[0] = v;
JTree tree = new JTree(genealogy);
tree.setRootVisible(true);
JScrollPane jsp = new JScrollPane(tree);
getContentPane().add(jsp);
}
}
Creating a JTree
public JTree()
JTree tree = new JTree();
public JTree(Hashtable value)
JTree tree = new JTree(System.getProperties());
public JTree(Object value[])
public static void main (String args[]) {
JTree tree = new JTree(args);
...
}
public JTree(Vector value)
Vector vector = new Vector();
vector.add("One");
vector.add("Two");
JTree tree = new JTree(vector);
public JTree(TreeModel value)
JTree tree = new JTree(aTreeModel);
public JTree(TreeNode value, boolean asksAllowsChildren)
JTree tree = new JTree(aTreeNode, true);
Creating a JTree Component
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root Label");
root.add(new DefaultMutableTreeNode("Node Label"));
JTree tree = new JTree(root);
JFrame f = new JFrame();
f.add(new JScrollPane(tree));
f.setSize(300,300);
f.setVisible(true);
}
}
Creating DefaultTreeCellEditor from its Default Tree Renderer
import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
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;
public class TreeEdit {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object array[] = {Boolean.TRUE, Boolean.FALSE, "Hello"};
JTree tree = new JTree(array);
tree.setEditable(true);
tree.setRootVisible(true);
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)tree.getCellRenderer();
String elements[] = { "A", "B", "C", "D"} ;
JComboBox comboBox = new JComboBox(elements);
comboBox.setEditable(true);
TreeCellEditor comboEditor = new DefaultCellEditor(comboBox);
TreeCellEditor editor = new DefaultTreeCellEditor(tree, renderer, comboEditor);
tree.setCellEditor(editor);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Drag and drop of a group of files into a tree
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class MyTree extends JTree {
public MyTree() {
super();
setDragEnabled(false);
setTransferHandler(new FSTransfer());
}
}
class FSTransfer extends TransferHandler {
public boolean importData(JComponent comp, Transferable t) {
if (!(comp instanceof MyTree)) {
return false;
}
if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
MyTree tree = (MyTree) comp;
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
try {
List data = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
Iterator i = data.iterator();
while (i.hasNext()) {
File f = (File) i.next();
root.add(new DefaultMutableTreeNode(f.getName()));
}
model.reload();
return true;
} catch (Exception ioe) {
System.out.println(ioe);
}
return false;
}
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
if (comp instanceof MyTree) {
for (int i = 0; i < transferFlavors.length; i++) {
if (!transferFlavors[i].equals(DataFlavor.javaFileListFlavor)) {
return false;
}
}
return true;
}
return false;
}
}
Dynamic Tree
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//package components;
/*
* This code is based on an example provided by Richard Stanford,
* a tutorial reader.
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
public class DynamicTreeDemo extends JPanel implements ActionListener {
private int newNodeSuffix = 1;
private static String ADD_COMMAND = "add";
private static String REMOVE_COMMAND = "remove";
private static String CLEAR_COMMAND = "clear";
private DynamicTree treePanel;
public DynamicTreeDemo() {
super(new BorderLayout());
// Create the components.
treePanel = new DynamicTree();
populateTree(treePanel);
JButton addButton = new JButton("Add");
addButton.setActionCommand(ADD_COMMAND);
addButton.addActionListener(this);
JButton removeButton = new JButton("Remove");
removeButton.setActionCommand(REMOVE_COMMAND);
removeButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
// Lay everything out.
treePanel.setPreferredSize(new Dimension(300, 150));
add(treePanel, BorderLayout.CENTER);
JPanel panel = new JPanel(new GridLayout(0, 3));
panel.add(addButton);
panel.add(removeButton);
panel.add(clearButton);
add(panel, BorderLayout.SOUTH);
}
public void populateTree(DynamicTree treePanel) {
String p1Name = new String("Parent 1");
String p2Name = new String("Parent 2");
String c1Name = new String("Child 1");
String c2Name = new String("Child 2");
DefaultMutableTreeNode p1, p2;
p1 = treePanel.addObject(null, p1Name);
p2 = treePanel.addObject(null, p2Name);
treePanel.addObject(p1, c1Name);
treePanel.addObject(p1, c2Name);
treePanel.addObject(p2, c1Name);
treePanel.addObject(p2, c2Name);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (ADD_COMMAND.equals(command)) {
// Add button clicked
treePanel.addObject("New Node " + newNodeSuffix++);
} else if (REMOVE_COMMAND.equals(command)) {
// Remove button clicked
treePanel.removeCurrentNode();
} else if (CLEAR_COMMAND.equals(command)) {
// Clear button clicked.
treePanel.clear();
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("DynamicTreeDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
DynamicTreeDemo newContentPane = new DynamicTreeDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: -
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. - Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. - Neither the name of Sun Microsystems nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// package components;
/*
* This code is based on an example provided by Richard Stanford, a tutorial
* reader.
*/
class DynamicTree extends JPanel {
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
protected JTree tree;
private Toolkit toolkit = Toolkit.getDefaultToolkit();
public DynamicTree() {
super(new GridLayout(1, 0));
rootNode = new DefaultMutableTreeNode("Root Node");
treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
}
/** Remove all nodes except the root node. */
public void clear() {
rootNode.removeAllChildren();
treeModel.reload();
}
/** Remove the currently selected node. */
public void removeCurrentNode() {
TreePath currentSelection = tree.getSelectionPath();
if (currentSelection != null) {
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection
.getLastPathComponent());
MutableTreeNode parent = (MutableTreeNode) (currentNode.getParent());
if (parent != null) {
treeModel.removeNodeFromParent(currentNode);
return;
}
}
// Either there was no selection, or the root was selected.
toolkit.beep();
}
/** Add child to the currently selected node. */
public DefaultMutableTreeNode addObject(Object child) {
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
} else {
parentNode = (DefaultMutableTreeNode) (parentPath.getLastPathComponent());
}
return addObject(parentNode, child, true);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child) {
return addObject(parent, child, false);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child, boolean shouldBeVisible) {
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
if (parent == null) {
parent = rootNode;
}
// It is key to invoke this on the TreeModel, and NOT DefaultMutableTreeNode
treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
// Make sure the user can see the lovely new node.
if (shouldBeVisible) {
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
}
return childNode;
}
class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode) (e.getTreePath().getLastPathComponent());
/*
* If the event lists children, then the changed node is the child of the
* node we"ve already gotten. Otherwise, the changed node and the
* specified node are the same.
*/
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode) (node.getChildAt(index));
System.out.println("The user has finished editing the node.");
System.out.println("New value: " + node.getUserObject());
}
public void treeNodesInserted(TreeModelEvent e) {
}
public void treeNodesRemoved(TreeModelEvent e) {
}
public void treeStructureChanged(TreeModelEvent e) {
}
}
}
Expansion and Collapse Events in a JTree are fired before a node is expanded or collapsed can be vetoed, thereby preventing the operation.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
public class Main {
public static void main() {
JTree tree = new JTree();
tree.addTreeWillExpandListener(new MyTreeWillExpandListener());
tree.addTreeExpansionListener(new MyTreeExpansionListener());
JFrame f = new JFrame();
f.add(new JScrollPane(tree));
f.setSize(300, 300);
f.setVisible(true);
}
}
class MyTreeWillExpandListener implements TreeWillExpandListener {
public void treeWillExpand(TreeExpansionEvent evt) throws ExpandVetoException {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
boolean veto = false;
if (veto) {
throw new ExpandVetoException(evt);
}
}
public void treeWillCollapse(TreeExpansionEvent evt) throws ExpandVetoException {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
boolean veto = false;
if (veto) {
throw new ExpandVetoException(evt);
}
}
}
class MyTreeExpansionListener implements TreeExpansionListener {
public void treeExpanded(TreeExpansionEvent evt) {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
System.out.println("treeExpanded");
}
public void treeCollapsed(TreeExpansionEvent evt) {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
System.out.println("treeCollapsed");
}
}
Finding a Node in a JTree Component
import javax.swing.JTree;
import javax.swing.text.Position;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String[] argv) throws Exception {
JTree tree = new JTree();
// Search forward from first visible row looking for any visible node
// whose name starts with prefix.
int startRow = 0;
String prefix = "b";
TreePath path = tree.getNextMatch(prefix, startRow, Position.Bias.Forward);
System.out.println(path);
}
}
Find the path regardless of visibility that matches the specified sequence of names
import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.text.Position;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String[] argv) throws Exception {
JTree tree = new JTree();
TreePath path = findByName(tree, new String[] { "JTree", "A", "a" });
}
public static TreePath findByName(JTree tree, String[] names) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
return find(tree, new TreePath(root), names, 0);
}
private static TreePath find(JTree tree, TreePath parent, Object[] nodes, int depth) {
TreeNode node = (TreeNode) parent.getLastPathComponent();
Object o = node;
if (o.equals(nodes[depth])) {
if (depth == nodes.length - 1) {
return parent;
}
if (node.getChildCount() >= 0) {
for (Enumeration e = node.children(); e.hasMoreElements();) {
TreeNode n = (TreeNode) e.nextElement();
TreePath path = parent.pathByAddingChild(n);
TreePath result = find(tree, path, nodes, depth + 1);
if (result != null) {
return result;
}
}
}
}
return null;
}
}
Have a popup attached to a JTree
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class Main extends JPanel {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root", true),
node1 = new DefaultMutableTreeNode("node 1", true), node2 = new DefaultMutableTreeNode(
"node 2", true), node3 = new DefaultMutableTreeNode("node 3", true);
MyJTree tree = new MyJTree(root);
public Main() {
root.add(node1);
node1.add(node2);
root.add(node3);
setLayout(new BorderLayout());
add(new JScrollPane((JTree) tree), "Center");
}
public static void main(String s[]) {
JFrame frame = new JFrame("Tree With Popup");
Main panel = new Main();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setBackground(Color.lightGray);
frame.getContentPane().add(panel, "Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyJTree extends JTree implements ActionListener {
JPopupMenu popup = new JPopupMenu();
JMenuItem mi = new JMenuItem("Insert a children");
MyJTree(DefaultMutableTreeNode dmtn) {
super(dmtn);
mi.addActionListener(this);
mi.setActionCommand("insert");
popup.add(mi);
mi = new JMenuItem("Remove this node");
mi.addActionListener(this);
mi.setActionCommand("remove");
popup.add(mi);
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show((JComponent) e.getSource(), e.getX(), e.getY());
}
}
});
}
public void actionPerformed(ActionEvent ae) {
DefaultMutableTreeNode dmtn, node;
TreePath path = this.getSelectionPath();
dmtn = (DefaultMutableTreeNode) path.getLastPathComponent();
if (ae.getActionCommand().equals("insert")) {
node = new DefaultMutableTreeNode("children");
dmtn.add(node);
((DefaultTreeModel) this.getModel()).nodeStructureChanged((TreeNode) dmtn);
}
if (ae.getActionCommand().equals("remove")) {
node = (DefaultMutableTreeNode) dmtn.getParent();
int nodeIndex = node.getIndex(dmtn);
dmtn.removeAllChildren();
node.remove(nodeIndex);
((DefaultTreeModel) this.getModel()).nodeStructureChanged((TreeNode) dmtn);
}
}
}
Have the row height for each row computed individually
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
public class TreeRowHeightCalculation {
public static void main(String[] argv) {
JTree tree = new JTree();
tree.setRowHeight(0);
JFrame frame = new JFrame("tree row height calculation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(tree));
frame.setSize(380, 320);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
JTree.DynamicUtilTreeNode Class
- The JTree class has an inner class, JTree.DynamicUtilTreeNode
- The JTree uses it to create the nodes for your trees.
- The DynamicUtilTreeNode is a DefaultMutableTreeNode subclass
- The DynamicUtilTreeNode doesn"t create its child nodes until they"re needed.
- The child nodes are needed when you either expand the parent node or try to traverse a tree.
import java.awt.BorderLayout;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class DynamicUtilTreeNodeDemo {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
hashtable.put ("Two", new String[]{"A", "B", "C"});
Hashtable<Object, Object> innerHashtable = new Hashtable<Object, Object>();
innerHashtable.put ("Two", new String[]{"A", "B", "C"});
hashtable.put ("Three", innerHashtable);
JTree.DynamicUtilTreeNode.createChildren(root, hashtable);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
JTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION)
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeSelectionModel;
public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("abcde");
DefaultMutableTreeNode node = new DefaultMutableTreeNode("1");
node.add(new DefaultMutableTreeNode("12345"));
node.add(new DefaultMutableTreeNode("testing"));
root.add(node);
root.add(new DefaultMutableTreeNode("1234567890"));
TreeModel tm = new DefaultTreeModel(root);
JTree tree = new JTree(tm);
tree.getSelectionModel().addTreeSelectionListener(new Selector());
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
getContentPane().add(tree, BorderLayout.CENTER);
pack();
setVisible(true);
}
private class Selector implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent event) {
Object obj = event.getNewLeadSelectionPath().getLastPathComponent();
System.out.println("" + obj.toString().length());
}
}
public static void main(String[] args) {
Main m = new Main();
}
}
JTree.lineStyle client property
The JTree.lineStyle property has the following valid settings:
- None :not drawing lines to connect nodes
- Angled :the default setting for Ocean, for drawing lines in the Tree.hash color to connect the nodes
- Horizontal:for drawing horizontal lines between first-level nodes in the Tree.line color
The JTree.lineStyle client property is used only by the Metal look and feel.
This client property is specific to tree components, and it is not set for all trees.
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
class TreeNodeVector<E> extends Vector<E> {
String name;
TreeNodeVector(String name) {
this.name = name;
}
TreeNodeVector(String name, E elements[]) {
this.name = name;
for (int i = 0, n = elements.length; i < n; i++) {
add(elements[i]);
}
}
public String toString() {
return "[" + name + "]";
}
}
public class ChangingTreeLineStyle {
public static void main(final String args[]) {
JFrame frame = new JFrame("JTreeSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v1 = new TreeNodeVector<String>("Two", new String[] { "Mercury", "Venus",
"Mars" });
Vector<Object> v2 = new TreeNodeVector<Object>("Three");
v2.add(System.getProperties());
v2.add(v1);
Object rootNodes[] = {v1, v2 };
Vector<Object> rootVector = new TreeNodeVector<Object>("Root", rootNodes);
JTree tree = new JTree(rootVector);
tree.putClientProperty("JTree.lineStyle", "None");
frame.add(new JScrollPane(tree), BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
JTree Look and Feel
Property StringObject TypeTree.actionMapActionMapTree.ancestorInputMapInputMapTree.backgroundColorTree.changeSelectionWithFocusBooleanTree.closedIconIconTree.collapsedIconIconTree.drawDashedFocusIndicatorBooleanTree.drawHorizontalLinesBooleanTree.drawsFocusBorderAroundIconBooleanTree.drawVerticalLinesBooleanTree.editorBorderBorderTree.editorBorderSelectionColorColorTree.expandedIconIconTree.expanderSizeIntegerTree.focusInputMapInputMapTree.focusInputMap.RightToLeftInputMapTree.fontFontTree.foregroundColorTree.hashColorTree.iconBackgroundColorTree.iconForegroundColorTree.iconHighlightColorTree.iconShadowColorTree.leafIconIconTree.leftChildIndentIntegerTree.lineColorTree.lineTypeDashedBooleanTree.openIconIconTree.paddingIntegerTree.paintLinesBooleanTree.rendererUseTreeColorsBooleanTree.rightChildIndentIntegerTree.rowHeightIntegerTree.scrollsHorizontallyAndVerticallyBooleanTree.scrollsOnExpandBooleanTree.selectionBackgroundColorTree.selectionBorderColorColorTree.selectionForegroundColorTree.showsRootHandlesBooleanTree.textBackgroundColorTree.textForegroundColorTree.timeFactorIntegerTreeUIString
Listening for Expansion and Collapse Events in a JTree Component
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
public class Main {
public static void main() {
JTree tree = new JTree();
tree.addTreeWillExpandListener(new MyTreeWillExpandListener());
tree.addTreeExpansionListener(new MyTreeExpansionListener());
JFrame f = new JFrame();
f.add(new JScrollPane(tree));
f.setSize(300, 300);
f.setVisible(true);
}
}
class MyTreeWillExpandListener implements TreeWillExpandListener {
public void treeWillExpand(TreeExpansionEvent evt) throws ExpandVetoException {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
boolean veto = false;
if (veto) {
throw new ExpandVetoException(evt);
}
}
public void treeWillCollapse(TreeExpansionEvent evt) throws ExpandVetoException {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
boolean veto = false;
if (veto) {
throw new ExpandVetoException(evt);
}
}
}
class MyTreeExpansionListener implements TreeExpansionListener {
public void treeExpanded(TreeExpansionEvent evt) {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
System.out.println("treeExpanded");
}
public void treeCollapsed(TreeExpansionEvent evt) {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
System.out.println("treeCollapsed");
}
}
Preventing Expansion or Collapse of a Node in a JTree: override JTree.setExpandedState()
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String[] argv) {
JTree tree = new JTree() {
protected void setExpandedState(TreePath path, boolean state) {
if (state) {
super.setExpandedState(path, state);
}
}
};
JFrame frame = new JFrame("Ignore all collapse requests");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(tree));
frame.setSize(380, 320);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Preventing the Expansion or Collapse of a Node in a JTree Component
import javax.swing.JTree;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String[] argv) {
JTree tree = new JTree() {
protected void setExpandedState(TreePath path, boolean state) {
if (state) {
super.setExpandedState(path, state);
}
}
};
}
}
Produce horizontal lines between level-one nodes
import java.awt.BorderLayout;
import java.awt.Color;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
class TreeNodeVector<E> extends Vector<E> {
String name;
TreeNodeVector(String name) {
this.name = name;
}
TreeNodeVector(String name, E elements[]) {
this.name = name;
for (int i = 0, n = elements.length; i < n; i++) {
add(elements[i]);
}
}
public String toString() {
return "[" + name + "]";
}
}
public class ChangingTreeLineStyleColorHorizontal {
public static void main(final String args[]) {
JFrame frame = new JFrame("JTreeSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v1 = new TreeNodeVector<String>("Two", new String[] { "Mercury", "Venus",
"Mars" });
Vector<Object> v2 = new TreeNodeVector<Object>("Three");
v2.add(System.getProperties());
v2.add(v1);
Object rootNodes[] = {v1, v2 };
Vector<Object> rootVector = new TreeNodeVector<Object>("Root", rootNodes);
JTree tree = new JTree(rootVector);
UIManager.put("Tree.line", Color.GREEN);
tree.putClientProperty("JTree.lineStyle", "Horizontal");
frame.add(new JScrollPane(tree), BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Scrolling Trees: public void scrollPathToVisible(TreePath path) and public void scrollRowToVisible(int row)
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
class TreeNodeVector<E> extends Vector<E> {
String name;
TreeNodeVector(String name) {
this.name = name;
}
TreeNodeVector(String name, E elements[]) {
this.name = name;
for (int i = 0, n = elements.length; i < n; i++) {
add(elements[i]);
}
}
public String toString() {
return "[" + name + "]";
}
}
public class TreeExpandRowAndMakeRowVisible {
public static void main(final String args[]) {
JFrame frame = new JFrame("JTreeSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v1 = new TreeNodeVector<String>("Two", new String[] { "Mercury", "Venus",
"Mars" });
Vector<Object> v2 = new TreeNodeVector<Object>("Three");
v2.add(System.getProperties());
v2.add(v1);
Object rootNodes[] = {v1, v2 };
Vector<Object> rootVector = new TreeNodeVector<Object>("Root", rootNodes);
JTree tree = new JTree(rootVector);
frame.add(new JScrollPane(tree), BorderLayout.CENTER);
tree.expandRow(1);
tree.scrollRowToVisible(2);
tree.revalidate();
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Search backward from last visible row looking for any visible node whose name starts with prefix.
import javax.swing.JTree;
import javax.swing.text.Position;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String[] argv) throws Exception {
JTree tree = new JTree();
int startRow = tree.getRowCount() - 1;
String prefix = "b";
TreePath path = tree.getNextMatch(prefix, startRow, Position.Bias.Backward);
System.out.println(path);
}
}
Setting the Row Height of a JTree
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
public class TreeRowHeight {
public static void main(String[] argv) {
JTree tree = new JTree();
tree.setRowHeight(15);
JFrame frame = new JFrame("tree row height");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(tree));
frame.setSize(380, 320);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
To find out when a tree node has been expanded or collapsed
public interface TreeExpansionListener implements EventListener {
public void treeCollapse(TreeExpansionEvent treeExpansionEvent);
public void treeExpand(TreeExpansionEvent treeExpansionEvent);
}
Traveling to all the nodes
- preOrderEnumeration(): The first node is the node itself. The next node is that node"s first child, then it"s the first child of that first child. Once a leaf node with no children is found, the next child of its parent is put in the Enumeration and its children are added to the list accordingly until no nodes are left.
- depthFirstEnumeration() and postOrderEnumeration(): Return an Enumeration that has practically the opposite behavior of preOrderEnumeration(). Instead of including the current node first and then adding the children, these methods add the children first and then add the current node to the Enumeration.
- breadthFirstEnumeration(): Returns an Enumeration of nodes added by level.
import java.awt.BorderLayout;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class PostPreorderAndDepthEnumeration {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.add(mercury);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
root.add(venus);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("Mars");
root.add(mars);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
Enumeration e = root.preorderEnumeration();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
e = root.postorderEnumeration();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
e = root.depthFirstEnumeration();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Traverse all expanded nodes in tree
import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String[] argv) throws Exception {
JTree tree = new JTree();
visitAllExpandedNodes(tree);
}
public static void visitAllExpandedNodes(JTree tree) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
visitAllExpandedNodes(tree, new TreePath(root));
}
public static void visitAllExpandedNodes(JTree tree, TreePath parent) {
if (!tree.isVisible(parent)) {
return;
}
TreeNode node = (TreeNode) parent.getLastPathComponent();
System.out.println(node);
if (node.getChildCount() >= 0) {
for (Enumeration e = node.children(); e.hasMoreElements();) {
TreeNode n = (TreeNode) e.nextElement();
TreePath path = parent.pathByAddingChild(n);
visitAllExpandedNodes(tree, path);
}
}
}
}
Traversing Trees
import java.awt.BorderLayout;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class PrintDescendants {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.add(mercury);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
root.add(venus);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("Mars");
root.add(mars);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
printDescendants(root);
}
public static void printDescendants(TreeNode root) {
System.out.println(root);
Enumeration children = root.children();
if (children != null) {
while (children.hasMoreElements()) {
printDescendants((TreeNode) children.nextElement());
}
}
}
}
Tree Will Expand Listener
public interface TreeWillExpandListener implements EventListener {
public void treeWillCollapse(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException;
public void treeWillExpand(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException;
}
Using Boolean value cell renderer to display boolean and non-boolean values
import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.TreeCellEditor;
public class TreeEdit {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object array[] = {Boolean.TRUE, Boolean.FALSE, "Hello"}; // Hello will map to false
JTree tree = new JTree(array);
tree.setEditable(true);
tree.setRootVisible(true);
JCheckBox checkBox = new JCheckBox();
TreeCellEditor editor = new DefaultCellEditor(checkBox);
tree.setCellEditor(editor);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Using Vector to store JTree values
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
class TreeNodeVector<E> extends Vector<E> {
String name;
TreeNodeVector(String name) {
this.name = name;
}
TreeNodeVector(String name, E elements[]) {
this.name = name;
for (int i = 0, n = elements.length; i < n; i++) {
add(elements[i]);
}
}
public String toString() {
return "[" + name + "]";
}
}
public class TreeArraySample {
public static void main(final String args[]) {
JFrame frame = new JFrame("JTreeSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v1 = new TreeNodeVector<String>("Two", new String[] { "Mercury", "Venus",
"Mars" });
Vector<Object> v2 = new TreeNodeVector<Object>("Three");
v2.add(System.getProperties());
v2.add(v1);
Object rootNodes[] = {v1, v2 };
Vector<Object> rootVector = new TreeNodeVector<Object>("Root", rootNodes);
JTree tree = new JTree(rootVector);
frame.add(new JScrollPane(tree), BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Visiting All the Nodes in a JTree Component
import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;
public class Main {
public static void main(String[] argv) throws Exception {
JTree tree = new JTree();
visitAllNodes(tree);
}
public static void visitAllNodes(JTree tree) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
visitAllNodes(root);
}
public static void visitAllNodes(TreeNode node) {
System.out.println(node);
if (node.getChildCount() >= 0) {
for (Enumeration e = node.children(); e.hasMoreElements();) {
TreeNode n = (TreeNode) e.nextElement();
visitAllNodes(n);
}
}
}
}
Working with the Nodes of the Tree
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class DefaultMutableTreeNodeDemo {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.insert(mercury, 0);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
root.insert(venus, 1);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("Mars");
root.insert(mars, 2);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}