Create Dynamic node for JTree in Java

Description

The following code shows how to create Dynamic node for JTree.

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.

Example


/*ww w .  j a va2 s. c  o m*/
 
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 Main {
  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 ("java2s.com", 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);

  }
}

The code above generates the following result.

Create Dynamic node for JTree in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer