Example usage for javax.swing.tree DefaultTreeModel insertNodeInto

List of usage examples for javax.swing.tree DefaultTreeModel insertNodeInto

Introduction

In this page you can find the example usage for javax.swing.tree DefaultTreeModel insertNodeInto.

Prototype

public void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) 

Source Link

Document

Invoked this to insert newChild at location index in parents children.

Usage

From source file:MyTreeModelListener.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    JTree tree = new JTree(root);

    DefaultTreeModel treeModel = new DefaultTreeModel(root);
    treeModel.addTreeModelListener(new MyTreeModelListener());

    treeModel.insertNodeInto(new DefaultMutableTreeNode("A"), root, 0);

    root.add(new DefaultMutableTreeNode("B"));
    root.add(new DefaultMutableTreeNode("C"));

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);/*from  w  w  w  .  j  av  a  2  s .co  m*/
    frame.setVisible(true);

}

From source file:MainClass.java

public static void main(String[] args) {
    // create a hierarchy of nodes
    MutableTreeNode root = new DefaultMutableTreeNode("A");
    MutableTreeNode bNode = new DefaultMutableTreeNode("B");
    MutableTreeNode cNode = new DefaultMutableTreeNode("C");
    root.insert(bNode, 0);/*  w w w .j  a  v a2s  .  co m*/
    root.insert(cNode, 1);
    bNode.insert(new DefaultMutableTreeNode("1"), 0);
    bNode.insert(new DefaultMutableTreeNode("2"), 1);
    cNode.insert(new DefaultMutableTreeNode("1"), 0);
    cNode.insert(new DefaultMutableTreeNode("2"), 1);

    final DefaultTreeModel model = new DefaultTreeModel(root);
    final JTree tree = new JTree(model);

    final JTextField nameField = new JTextField("Z");
    final JButton button = new JButton("Add");
    button.setEnabled(false);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            TreePath tp = tree.getSelectionPath();
            MutableTreeNode insertNode = (MutableTreeNode) tp.getLastPathComponent();
            int insertIndex = 0;
            if (insertNode.getParent() != null) {
                MutableTreeNode parent = (MutableTreeNode) insertNode.getParent();
                insertIndex = parent.getIndex(insertNode) + 1;
                insertNode = parent;
            }
            MutableTreeNode node = new DefaultMutableTreeNode(nameField.getText());
            model.insertNodeInto(node, insertNode, insertIndex);
        }
    });
    JPanel addPanel = new JPanel(new GridLayout(2, 1));
    addPanel.add(nameField);
    addPanel.add(button);

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            TreePath tp = e.getNewLeadSelectionPath();
            button.setEnabled(tp != null);
        }
    });

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.getContentPane().add(new JScrollPane(tree));
    frame.getContentPane().add(addPanel, BorderLayout.SOUTH);
    frame.setVisible(true);
}

From source file:MainClass.java

public static void main(String[] args) {
    MutableTreeNode root = new DefaultMutableTreeNode("A");
    MutableTreeNode beams = new DefaultMutableTreeNode("B");
    MutableTreeNode gears = new DefaultMutableTreeNode("C");
    root.insert(beams, 0);/* w ww .  java2  s .  c  o  m*/
    root.insert(gears, 1);
    beams.insert(new DefaultMutableTreeNode("4 "), 0);
    beams.insert(new DefaultMutableTreeNode("6 "), 1);
    beams.insert(new DefaultMutableTreeNode("8 "), 2);
    beams.insert(new DefaultMutableTreeNode("12 "), 3);
    gears.insert(new DefaultMutableTreeNode("8t"), 0);
    gears.insert(new DefaultMutableTreeNode("24t"), 1);
    gears.insert(new DefaultMutableTreeNode("40t"), 2);

    final DefaultTreeModel model = new DefaultTreeModel(root);
    final JTree tree = new JTree(model);

    final JTextField nameField = new JTextField("16t");
    final JButton button = new JButton("Add a part");
    button.setEnabled(false);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            TreePath tp = tree.getSelectionPath();
            MutableTreeNode insertNode = (MutableTreeNode) tp.getLastPathComponent();
            int insertIndex = 0;
            if (insertNode.getParent() != null) {
                MutableTreeNode parent = (MutableTreeNode) insertNode.getParent();
                insertIndex = parent.getIndex(insertNode) + 1;
                insertNode = parent;
            }
            MutableTreeNode node = new DefaultMutableTreeNode(nameField.getText());
            model.insertNodeInto(node, insertNode, insertIndex);
        }
    });
    JPanel addPanel = new JPanel(new GridLayout(2, 1));
    addPanel.add(nameField);
    addPanel.add(button);

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            TreePath tp = e.getNewLeadSelectionPath();
            button.setEnabled(tp != null);
        }
    });

    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.getContentPane().add(new JScrollPane(tree));
    frame.getContentPane().add(addPanel, BorderLayout.SOUTH);
    frame.setVisible(true);
}

From source file:DndTree.java

public static void main(String args[]) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel top = new JPanel(new BorderLayout());
    JLabel dragLabel = new JLabel("Drag me:");
    JTextField text = new JTextField();
    text.setDragEnabled(true);//from   ww w  . j ava  2  s .co  m
    top.add(dragLabel, BorderLayout.WEST);
    top.add(text, BorderLayout.CENTER);
    f.add(top, BorderLayout.NORTH);

    final JTree tree = new JTree();
    final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    tree.setTransferHandler(new TransferHandler() {
        public boolean canImport(TransferHandler.TransferSupport support) {
            if (!support.isDataFlavorSupported(DataFlavor.stringFlavor) || !support.isDrop()) {
                return false;
            }
            JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
            return dropLocation.getPath() != null;
        }

        public boolean importData(TransferHandler.TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }
            JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
            TreePath path = dropLocation.getPath();
            Transferable transferable = support.getTransferable();

            String transferData;
            try {
                transferData = (String) transferable.getTransferData(DataFlavor.stringFlavor);
            } catch (IOException e) {
                return false;
            } catch (UnsupportedFlavorException e) {
                return false;
            }

            int childIndex = dropLocation.getChildIndex();
            if (childIndex == -1) {
                childIndex = model.getChildCount(path.getLastPathComponent());
            }

            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(transferData);
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            model.insertNodeInto(newNode, parentNode, childIndex);

            TreePath newPath = path.pathByAddingChild(newNode);
            tree.makeVisible(newPath);
            tree.scrollRectToVisible(tree.getPathBounds(newPath));
            return true;
        }
    });

    JScrollPane pane = new JScrollPane(tree);
    f.add(pane, BorderLayout.CENTER);

    tree.setDropMode(DropMode.USE_SELECTION);
    f.setSize(300, 400);
    f.setVisible(true);
}

From source file:DndTree.java

public static void main(String args[]) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel top = new JPanel(new BorderLayout());
    JLabel dragLabel = new JLabel("Drag me:");
    JTextField text = new JTextField();
    text.setDragEnabled(true);/*from w ww . j  a va  2 s. co m*/
    top.add(dragLabel, BorderLayout.WEST);
    top.add(text, BorderLayout.CENTER);
    f.add(top, BorderLayout.NORTH);

    final JTree tree = new JTree();
    final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    tree.setTransferHandler(new TransferHandler() {
        public boolean canImport(TransferHandler.TransferSupport support) {
            if (!support.isDataFlavorSupported(DataFlavor.stringFlavor) || !support.isDrop()) {
                return false;
            }
            JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
            return dropLocation.getPath() != null;
        }

        public boolean importData(TransferHandler.TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }
            JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
            TreePath path = dropLocation.getPath();
            Transferable transferable = support.getTransferable();

            String transferData;
            try {
                transferData = (String) transferable.getTransferData(DataFlavor.stringFlavor);
            } catch (IOException e) {
                return false;
            } catch (UnsupportedFlavorException e) {
                return false;
            }

            int childIndex = dropLocation.getChildIndex();
            if (childIndex == -1) {
                childIndex = model.getChildCount(path.getLastPathComponent());
            }

            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(transferData);
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            model.insertNodeInto(newNode, parentNode, childIndex);

            TreePath newPath = path.pathByAddingChild(newNode);
            tree.makeVisible(newPath);
            tree.scrollRectToVisible(tree.getPathBounds(newPath));
            return true;
        }
    });

    JScrollPane pane = new JScrollPane(tree);
    f.add(pane, BorderLayout.CENTER);

    tree.setDropMode(DropMode.INSERT);
    f.setSize(300, 400);
    f.setVisible(true);
}

From source file:DndTree.java

public static void main(String args[]) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel top = new JPanel(new BorderLayout());
    JLabel dragLabel = new JLabel("Drag me:");
    JTextField text = new JTextField();
    text.setDragEnabled(true);//  ww w  .  ja  v a 2  s.com
    top.add(dragLabel, BorderLayout.WEST);
    top.add(text, BorderLayout.CENTER);
    f.add(top, BorderLayout.NORTH);

    final JTree tree = new JTree();
    final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    tree.setTransferHandler(new TransferHandler() {
        public boolean canImport(TransferHandler.TransferSupport support) {
            if (!support.isDataFlavorSupported(DataFlavor.stringFlavor) || !support.isDrop()) {
                return false;
            }
            JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
            return dropLocation.getPath() != null;
        }

        public boolean importData(TransferHandler.TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }
            JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
            TreePath path = dropLocation.getPath();
            Transferable transferable = support.getTransferable();

            String transferData;
            try {
                transferData = (String) transferable.getTransferData(DataFlavor.stringFlavor);
            } catch (IOException e) {
                return false;
            } catch (UnsupportedFlavorException e) {
                return false;
            }

            int childIndex = dropLocation.getChildIndex();
            if (childIndex == -1) {
                childIndex = model.getChildCount(path.getLastPathComponent());
            }

            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(transferData);
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            model.insertNodeInto(newNode, parentNode, childIndex);

            TreePath newPath = path.pathByAddingChild(newNode);
            tree.makeVisible(newPath);
            tree.scrollRectToVisible(tree.getPathBounds(newPath));
            return true;
        }
    });

    JScrollPane pane = new JScrollPane(tree);
    f.add(pane, BorderLayout.CENTER);

    tree.setDropMode(DropMode.ON_OR_INSERT);
    f.setSize(300, 400);
    f.setVisible(true);
}

From source file:Main.java

protected void addFiles(File rootFile, DefaultTreeModel model, DefaultMutableTreeNode root) {
    for (File file : rootFile.listFiles()) {
        DefaultMutableTreeNode child = new DefaultMutableTreeNode(file);
        model.insertNodeInto(child, root, root.getChildCount());
        if (file.isDirectory()) {
            addFiles(file, model, child);
        }//from w w w  .  java2s.c  o m
    }
}

From source file:TreeDragTest.java

public void drop(DropTargetDropEvent dtde) {
    Point pt = dtde.getLocation();
    DropTargetContext dtc = dtde.getDropTargetContext();
    JTree tree = (JTree) dtc.getComponent();
    TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) parentpath.getLastPathComponent();
    if (parent.isLeaf()) {
        dtde.rejectDrop();//from w  w  w. j a  v a 2 s.c o  m
        return;
    }

    try {
        Transferable tr = dtde.getTransferable();
        DataFlavor[] flavors = tr.getTransferDataFlavors();
        for (int i = 0; i < flavors.length; i++) {
            if (tr.isDataFlavorSupported(flavors[i])) {
                dtde.acceptDrop(dtde.getDropAction());
                TreePath p = (TreePath) tr.getTransferData(flavors[i]);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
                DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                model.insertNodeInto(node, parent, 0);
                dtde.dropComplete(true);
                return;
            }
        }
        dtde.rejectDrop();
    } catch (Exception e) {
        e.printStackTrace();
        dtde.rejectDrop();
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.security.NavigationTreeContextMenuMgr.java

/**
 * @param node/*from www.  j a  v  a  2s. c  o  m*/
 */
private void addToAdminGroup(final DefaultMutableTreeNode node) {
    if (node != null) {
        Object userObject = node.getUserObject();
        if (userObject != null) {
            FormDataObjIFace dmObject = ((DataModelObjBaseWrapper) userObject).getDataObj();
            if (dmObject != null && dmObject instanceof SpecifyUser) {
                SpPrincipal adminPrin = null;
                DataProviderSessionIFace session = null;
                try {
                    session = DataProviderFactory.getInstance().createSession();
                    adminPrin = (SpPrincipal) session.getData(SpPrincipal.class, "name", "Administrator",
                            DataProviderSessionIFace.CompareType.Equals);
                    if (adminPrin != null) {
                        SpecifyUser spUser = session.get(SpecifyUser.class, ((SpecifyUser) dmObject).getId());
                        spUser.addUserToSpPrincipalGroup(adminPrin);

                        session.beginTransaction();
                        session.saveOrUpdate(spUser);
                        session.saveOrUpdate(adminPrin);
                        session.commit();

                        DefaultMutableTreeNode adminNode = getAdminTreeNode(
                                (DefaultMutableTreeNode) treeMgr.getTree().getModel().getRoot());
                        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
                                new DataModelObjBaseWrapper(spUser));

                        DefaultTreeModel model = (DefaultTreeModel) getTree().getModel();
                        model.insertNodeInto(newNode, adminNode, adminNode.getChildCount());
                        model.nodeChanged(adminNode);
                        model.nodeChanged(newNode);
                        getTree().repaint();

                        getTree().setSelectionPath(new TreePath(newNode.getPath()));

                        lastClickComp = null;
                        updateBtnUI();
                    }

                } catch (final Exception e1) {
                    e1.printStackTrace();

                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(NavigationTreeMgr.class, e1);
                    session.rollback();

                } finally {
                    if (session != null) {
                        session.close();
                    }
                }
            }
        }
    }
}

From source file:Main.java

public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TreeNode root = getNodes();//from   w w w .  ja  v a 2  s  .c om
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(model);
    tree.setRootVisible(false);

    JButton add = new JButton("add new");
    add.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        MyObject newChild = new MyObject(obj.name + "-" + (obj.childs.size() + 1));
        obj.childs.add(newChild);
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newChild);
        model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
        TreeNode[] nodes = model.getPathToRoot(newNode);
        TreePath path = new TreePath(nodes);
        tree.scrollPathToVisible(path);
    });

    JButton print = new JButton("print childs");
    print.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        System.out.println(obj.childs);
    });
    JPanel btns = new JPanel();
    btns.add(add);
    btns.add(print);

    add(new JScrollPane(tree));
    add(btns, BorderLayout.SOUTH);
    pack();
    setVisible(true);
}