Java Swing How to - Create Button-Tree from JTree








Question

We would like to know how to create Button-Tree from JTree.

Answer

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Container;
import java.awt.GridLayout;
/*from  www  . ja v a2  s .c  o m*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class Main extends JPanel {
  JTree menuTree;
  JPanel buttonPanel;

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    new Main().initContainer(frame);
    frame.pack();
    frame.setVisible(true);
  }

  void initContainer(Container container) {
    container.setLayout(new GridLayout(1, 0));
    buttonPanel = new JPanel(new GridLayout(0, 1));
    Object[] menuNames = {
        "ROOT",
        new Object[] { "A",
            new Object[] { "CSS", "HTML", "SQL", "Java" }, "Code",
            new Object[] { "Test", "S", "C" } },
        new Object[] { "Code 1",
            new Object[] { "A", "I", "H", "O" }, "Code",
            new Object[] { "P", "S", "C" },"C" } };

    DefaultMutableTreeNode currentNode = processHierarchy(menuNames);
    menuTree = new JTree(currentNode);
    menuTree.setVisibleRowCount(10);
    menuTree.expandRow(2);
    initializeButtons(currentNode);
    container.add(buttonPanel, BorderLayout.WEST);
    container.add(new JScrollPane(menuTree), BorderLayout.EAST);
    menuTree.addTreeSelectionListener(e -> {
      initializeButtons((DefaultMutableTreeNode) menuTree
          .getLastSelectedPathComponent());
    });
  }

  private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);
    DefaultMutableTreeNode child;
    for (int i = 1; i < hierarchy.length; i++) {
      Object nodeSpecifier = hierarchy[i];
      if (nodeSpecifier instanceof Object[]) {
        child = processHierarchy((Object[]) nodeSpecifier);
      } else {
        child = new DefaultMutableTreeNode(nodeSpecifier);
      }
      node.add(child);
    }
    return (node);
  }

  private void initializeButtons(DefaultMutableTreeNode node) {
    Button b;
    buttonPanel.removeAll();
    for (int i = 0; i < node.getChildCount(); i++) {
      b = new Button();
      b.setLabel("" + node.getChildAt(i));
      buttonPanel.add(b);
      buttonPanel.revalidate();
    }
  }
}