Example usage for javax.swing.tree DefaultMutableTreeNode add

List of usage examples for javax.swing.tree DefaultMutableTreeNode add

Introduction

In this page you can find the example usage for javax.swing.tree DefaultMutableTreeNode add.

Prototype

public void add(MutableTreeNode newChild) 

Source Link

Document

Removes newChild from its parent and makes it a child of this node by adding it to the end of this node's child array.

Usage

From source file:dnd.BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    //Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    //LEFT COLUMN
    //Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    //Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    //RIGHT COLUMN
    //Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    //Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    //Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setVisibleRowCount(-1);//from   w ww.j a  v  a 2  s  . c om
    list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    list.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) list.getModel();
            int index = dl.getIndex();
            boolean insert = dl.isInsert();
            // Get the current string under the drop.
            String value = (String) listModel.getElementAt(index);

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // Display a dialog with the drop information.
            String dropValue = "\"" + data + "\" dropped ";
            if (dl.isInsert()) {
                if (dl.getIndex() == 0) {
                    displayDropLocation(dropValue + "at beginning of list");
                } else if (dl.getIndex() >= list.getModel().getSize()) {
                    displayDropLocation(dropValue + "at end of list");
                } else {
                    String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1);
                    String value2 = (String) list.getModel().getElementAt(dl.getIndex());
                    displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\"");
                }
            } else {
                displayDropLocation(dropValue + "on top of " + "\"" + value + "\"");
            }

            /**  This is commented out for the basicdemo.html tutorial page.
                       **  If you add this code snippet back and delete the
                       **  "return false;" line, the list will accept drops
                       **  of type string.
                      // Perform the actual import.  
                      if (insert) {
            listModel.add(index, data);
                      } else {
            listModel.set(index, data);
                      }
                      return true;
            */
            return false;
        }

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    list.setDropMode(DropMode.ON_OR_INSERT);

    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    //Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    //Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:edu.mbl.jif.datasetconvert.CheckboxTreeDimensions.java

protected TreeModel getDimensionsTreeModel(JSONObject sumMD_In) {
    try {/*from w  w w .j  a  v a  2 s.  c o m*/
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("All");
        DefaultMutableTreeNode parent;
        DimensionalExtents dsdIn = SumMetadata.getDimensionalExtents(sumMD_In);
        parent = new DefaultMutableTreeNode("Channel");
        root.add(parent);
        channelNamesOriginal = SumMetadata.getChannelNames(sumMD_In);
        for (int chan = 0; chan < dsdIn.numChannels; chan++) {
            parent.add(new DefaultMutableTreeNode(channelNamesOriginal[chan]));
        }
        if (dsdIn.numSlices > 1) {
            parent = new DefaultMutableTreeNode("Z-Section");
            root.add(parent);
            for (int slice = 0; slice < dsdIn.numSlices; slice++) {
                parent.add(new DefaultMutableTreeNode(slice));
            }
        }
        if (dsdIn.numFrames > 1) {
            parent = new DefaultMutableTreeNode("TimePoint");
            root.add(parent);
            for (int frame = 0; frame < dsdIn.numFrames; frame++) {
                parent.add(new DefaultMutableTreeNode(frame));
            }
        }
        if (dsdIn.numPositions > 1) {
            parent = new DefaultMutableTreeNode("Position");
            root.add(parent);
            for (int pos = 0; pos < dsdIn.numPositions; pos++) {
                parent.add(new DefaultMutableTreeNode(pos));
            }
        }
        return new DefaultTreeModel(root);
    } catch (Exception ex) {
        Logger.getLogger(CheckboxTreeDimensions.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:net.landora.animeinfo.notifications.NotificationViewer.java

public void loadNotifications() {
    List<AnimeNotification> notifications = AnimeDBA.getOutstandAnimeNotifications();

    Set<AnimeStub> animes = new HashSet<AnimeStub>();
    for (AnimeNotification notification : notifications) {
        animes.add(notification.getFile().getEpisode().getAnime());
    }//from w  w  w. j  av  a2  s .  c om

    List<AnimeStub> sortedAnime = new ArrayList<AnimeStub>(animes);
    Collections.sort(sortedAnime, UIUtils.LEXICAL_SORTER);

    notificationsNode.removeAllChildren();

    for (AnimeStub anime : sortedAnime) {
        DefaultMutableTreeNode animeNode = new DefaultMutableTreeNode(anime);

        MultiValueMap map = new MultiValueMap();
        for (AnimeNotification notificaton : notifications) {
            if (notificaton.getFile().getEpisode().getAnime().equals(anime)) {
                map.put(notificaton.getFile().getEpisode(), notificaton);
            }
        }
        List<AnimeEpisode> episodes = new ArrayList<AnimeEpisode>(map.keySet());
        Collections.sort(episodes, UIUtils.LEXICAL_SORTER);

        for (AnimeEpisode episode : episodes) {
            DefaultMutableTreeNode episodeNode = new DefaultMutableTreeNode(episode);
            List<AnimeNotification> list = (List<AnimeNotification>) map.get(episode);
            Collections.sort(list, UIUtils.LEXICAL_SORTER);
            for (AnimeNotification notification : list) {
                episodeNode.add(new DefaultMutableTreeNode(notification, false));
            }
            animeNode.add(episodeNode);
        }
        notificationsNode.add(animeNode);
    }

    treeModel.nodeStructureChanged(notificationsNode);
}

From source file:BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    // Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    // LEFT COLUMN
    // Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    // Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    // RIGHT COLUMN
    // Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    // Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    // Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setVisibleRowCount(-1);//from ww  w.j a  va  2s  .  co  m
    list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    list.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) list.getModel();
            int index = dl.getIndex();
            boolean insert = dl.isInsert();
            // Get the current string under the drop.
            String value = (String) listModel.getElementAt(index);

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // Display a dialog with the drop information.
            String dropValue = "\"" + data + "\" dropped ";
            if (dl.isInsert()) {
                if (dl.getIndex() == 0) {
                    displayDropLocation(dropValue + "at beginning of list");
                } else if (dl.getIndex() >= list.getModel().getSize()) {
                    displayDropLocation(dropValue + "at end of list");
                } else {
                    String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1);
                    String value2 = (String) list.getModel().getElementAt(dl.getIndex());
                    displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\"");
                }
            } else {
                displayDropLocation(dropValue + "on top of " + "\"" + value + "\"");
            }

            /**
             * This is commented out for the basicdemo.html tutorial page. * If you
             * add this code snippet back and delete the * "return false;" line, the
             * list will accept drops * of type string. // Perform the actual
             * import. if (insert) { listModel.add(index, data); } else {
             * listModel.set(index, data); } return true;
             */
            return false;
        }

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    list.setDropMode(DropMode.ON_OR_INSERT);

    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    // Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    // Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:org.netxilia.server.rest.HomeResource.java

/**
 * build the HTML tags for a tree like view
 * //  w ww .  ja  v a2 s. com
 * @param foldersSheet
 * @param treeview
 * @throws NetxiliaBusinessException
 * @throws NetxiliaResourceException
 */
private DefaultMutableTreeNode buildWorkbookTree(IWorkbook workbook, ISheet foldersSheet,
        Set<SheetFullName> sheetNames) throws NetxiliaResourceException, NetxiliaBusinessException {
    DefaultMutableTreeNode workbookNode = new DefaultMutableTreeNode(
            new TreeViewData(workbook.getId().getKey(), workbook.getName(), "workbook"));

    Stack<DefaultMutableTreeNode> stockNodes = new Stack<DefaultMutableTreeNode>();
    stockNodes.push(workbookNode);

    Set<SheetFullName> alreadyInsertedSheets = new HashSet<SheetFullName>();
    if (foldersSheet != null) {
        Matrix<CellData> folderCells = foldersSheet.receiveCells(AreaReference.ALL).getNonBlocking();
        for (List<CellData> row : folderCells.getRows()) {
            int level = 0;
            String nodeName = null;
            for (CellData cell : row) {
                if (cell.getValue() != null) {
                    nodeName = cell.getValue().getStringValue();
                    if (nodeName != null && nodeName.length() > 0) {
                        level = cell.getReference().getColumnIndex();
                        break;
                    }
                }
            }

            if (nodeName == null) {
                // empty line - ignored
                continue;
            }

            // first level for folders is 1 (under the root node)
            level = level + 1;
            SheetFullName sheetName = new SheetFullName(workbook.getName(), nodeName);
            boolean isSheet = sheetNames.contains(sheetName);
            if (isSheet) {
                alreadyInsertedSheets.add(sheetName);
            }
            DefaultMutableTreeNode crt = new DefaultMutableTreeNode(new TreeViewData(sheetName.toString(),
                    sheetName.getSheetName(), isSheet ? "sheet" : "folder"));
            while (!stockNodes.empty()) {
                DefaultMutableTreeNode node = stockNodes.peek();
                if (level > node.getLevel()) {
                    // make sure is the direct child
                    node.add(crt);
                    break;
                }
                stockNodes.pop();
            }
            stockNodes.push(crt);
        }
    }
    // add the sheets not already added
    for (SheetFullName sheetName : sheetNames) {
        if (alreadyInsertedSheets.contains(sheetName)) {
            continue;
        }
        DefaultMutableTreeNode sheetNode = new DefaultMutableTreeNode(
                new TreeViewData(sheetName.toString(), sheetName.getSheetName(), "sheet"));
        workbookNode.add(sheetNode);
    }

    return workbookNode;
}

From source file:TestTree.java

public void init() {
    // Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because
    // the/*  w w w  . j a  va  2 s .c  om*/
    // DefaultTreeModel can use it to build a complete tree.
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");

    // Build our tree model starting at the root node, and then make a JTree
    // out
    // of that.
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);

    // Build the tree up from the nodes we created.
    treeModel.insertNodeInto(subroot, root, 0);
    // Or, more succinctly:
    subroot.add(leaf1);
    root.add(leaf2);

    // Display it.
    getContentPane().add(tree, BorderLayout.CENTER);
}

From source file:com.tascape.qa.th.android.driver.App.java

private DefaultMutableTreeNode createNode(UIANode uiNode) {
    Rect bounds = uiNode.getBounds();/*from  ww  w . j  a  va 2 s. c om*/
    String s = uiNode.getKlass() + " " + uiNode.getContentDescription() + " "
            + String.format("[%d,%d][%d,%d]", bounds.left, bounds.top, bounds.right, bounds.bottom);
    DefaultMutableTreeNode tNode = new DefaultMutableTreeNode(s);
    tNode.setUserObject(uiNode);

    for (UIANode n : uiNode.nodes()) {
        tNode.add(createNode(n));
    }
    return tNode;
}

From source file:gtu._work.ui.LoadJspCheckTagUI.java

private void setTreeNode(Map<Tag, Set<File>> map) {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    DefaultMutableTreeNode child = null;
    DefaultMutableTreeNode childchild = null;
    List<Tag> list = new ArrayList<Tag>(map.keySet());
    List<File> childList = null;
    Collections.sort(list);/*from  w w  w .ja va 2  s.c  om*/
    for (Tag tagName : list) {
        child = new DefaultMutableTreeNode();
        child.setUserObject(tagName);
        root.add(child);
        childList = new ArrayList<File>(map.get(tagName));
        Collections.sort(childList);
        for (File chfile : childList) {
            childchild = new DefaultMutableTreeNode();
            childchild.setUserObject(new ChieldNode(chfile));
            child.add(childchild);
        }
    }
    jTree1.setModel(new DefaultTreeModel(root));
}

From source file:it.unibas.spicygui.controllo.window.operator.ProjectTreeGenerator.java

private void createInstanceChild(DefaultMutableTreeNode nodeTopComponent, IDataSourceProxy source,
        String type) {/* www.j  a  va 2 s. c o  m*/

    TreeTopComponentAdapter ttcaFirst = new TreeTopComponentAdapter(null, false, false, true);
    DefaultMutableTreeNode nodeChildFirst = new DefaultMutableTreeNode(ttcaFirst);
    ttcaFirst.setName(type);
    nodeTopComponent.add(nodeChildFirst);
    createInstacesNode(source, nodeChildFirst);
}

From source file:it.cnr.icar.eric.client.ui.swing.ConceptsTreeModel.java

public void insertConcept(Concept concept, DefaultMutableTreeNode parentNode) {
    NodeInfo nodeInfo = new NodeInfo();
    nodeInfo.obj = concept;/*from   w w w.  j  a v  a  2  s .  co m*/
    nodeInfo.loaded = false;

    @SuppressWarnings("unused")
    ConceptsTreeNode newNode = new ConceptsTreeNode(nodeInfo);

    // insertNodeInto(newNode, rootNode, rootNode.getChildCount());
    parentNode.add(new ConceptsTreeNode(nodeInfo));
    reload(parentNode);
}