Example usage for javax.swing.tree DefaultTreeModel getRoot

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

Introduction

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

Prototype

public Object getRoot() 

Source Link

Document

Returns the root of the tree.

Usage

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    CheckBoxNode accessibilityOptions[] = { new CheckBoxNode("A", false), new CheckBoxNode("B", true) };
    CheckBoxNode browsingOptions[] = { new CheckBoxNode("C", true), new CheckBoxNode("D", true),
            new CheckBoxNode("E", true), new CheckBoxNode("F", false) };
    Vector accessVector = new NamedVector("G", accessibilityOptions);
    Vector browseVector = new NamedVector("H", browsingOptions);
    Object rootNodes[] = { accessVector, browseVector };
    Vector rootVector = new NamedVector("Root", rootNodes);
    tree = new JTree(rootVector);

    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
    tree.setCellRenderer(renderer);//from ww w  .j  a v  a  2  s  .c  o  m

    tree.setCellEditor(new CheckBoxNodeEditor(tree));
    tree.setEditable(true);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.getContentPane().add(scrollPane, BorderLayout.NORTH);

    JPanel buttonPanel = new JPanel();
    JButton button = new JButton("new node");
    buttonPanel.add(button);
    frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    button.addActionListener(e -> {
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New node");
        root.add(newNode);
        model.reload();
    });

    frame.setSize(300, 450);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame(Main.class.getSimpleName());
    DefaultTreeModel model = getTreeModel();
    JTree tree1 = new JTree(model);
    JTree tree2 = new JTree(model);
    frame.add(new JScrollPane(tree1), BorderLayout.WEST);
    frame.add(new JScrollPane(tree2), BorderLayout.EAST);
    frame.pack();/*from  ww w  .  j a  v  a2  s. com*/
    frame.setSize(frame.getWidth() + 50, frame.getHeight() + 140);
    frame.setVisible(true);
    Timer t = new Timer(2000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
            root.add(new DefaultMutableTreeNode("A new node"));
            model.nodesWereInserted(root, new int[] { root.getChildCount() - 1 });
            tree1.expandRow(0);
            tree2.expandRow(0);
            frame.revalidate();
        }
    });
    t.start();
}

From source file:Main.java

private void buildTreeFromString(final DefaultTreeModel model, final String str) {
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    String[] strings = str.split("/");
    DefaultMutableTreeNode node = root;
    for (String s : strings) {
        int index = childIndex(node, s);
        if (index < 0) {
            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(s);
            node.insert(newChild, node.getChildCount());
            node = newChild;/*from  ww  w. j a va 2 s  .com*/
        } else {
            node = (DefaultMutableTreeNode) node.getChildAt(index);
        }
    }
}

From source file:MyTree.java

public boolean importData(JComponent comp, Transferable t) {
    if (!(comp instanceof MyTree)) {
        return false;
    }/*from w w w .j  a v  a  2  s  . c  om*/
    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;
}

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

public void generateTree(JTree jTree, Scenario scenario, String stringa) {
    DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
    TreeNode root = (TreeNode) model.getRoot();
    if (root != null) {
        analisiRicorsivaAggiuntaIstanza(root, scenario, model, stringa);
    }//from  w ww  .  jav  a 2s .c o m
}

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

public void generateTree(JTree jTree, Scenario scenario, TopComponent topComponentAdded) {
    Scenarios scenarios = (Scenarios) modello.getBean(Costanti.SCENARIOS);
    DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
    TreeNode root = (TreeNode) model.getRoot();
    if (root != null) {
        if (topComponentAdded != null) {
            analisiRicorsivaAggiuntaTC(root, scenario, model, topComponentAdded);
        } else if (scenarios.containsScenario(scenario)) {
            analizzaScenario((DefaultMutableTreeNode) root, scenario);
        } else {// w  w w.j a va2  s . c om
            analisiRicorsivaCancellaScenario(root, scenario, model);
        }
    }
}

From source file:com.compomics.cell_coord.gui.controller.load.LoadTracksController.java

/**
 * Load the data files into the tree.//w ww .j  av a2s  .com
 *
 * @throws LoadDirectoryException - when the directory is empty!
 */
private void loadDataIntoTree() throws LoadDirectoryException {
    DefaultTreeModel model = (DefaultTreeModel) loadTracksPanel.getDirectoryTree().getModel();
    DefaultMutableTreeNode rootNote = (DefaultMutableTreeNode) model.getRoot();
    // change name (user object) of root node
    rootNote.setUserObject(directory.getName());
    File[] listFiles = directory.listFiles();
    if (listFiles.length != 0) {
        for (File file : listFiles) {
            if (!file.isDirectory()) {
                DefaultMutableTreeNode fileNode = new DefaultMutableTreeNode(file.getName(), Boolean.FALSE);
                rootNote.add(fileNode);
            } else {
                // reset the directory to null
                directory = null;
                throw new LoadDirectoryException("This directory has a wrong structure!");
            }
        }
    } else {
        // reset the directory to null
        directory = null;
        throw new LoadDirectoryException("This directory seems to be empty!");
    }
    model.reload();
    loadTracksPanel.getChosenDirectoryTextArea().setText(directory.getAbsolutePath());
    cellCoordController.showMessage("Directory successful loaded!\nYou can now select the files to import!", "",
            JOptionPane.INFORMATION_MESSAGE);
    loadTracksPanel.getImportFilesButton().setEnabled(true);
}

From source file:com.imaginea.betterdocs.BetterDocsAction.java

public void runAction(final AnActionEvent e) throws IOException {
    final Editor projectEditor = DataKeys.EDITOR.getData(e.getDataContext());

    if (projectEditor != null) {

        Set<String> imports = getImports(projectEditor.getDocument());
        Set<String> lines = getLines(projectEditor, projectEditor.getDocument());
        Set<String> importsInLines = importsInLines(lines, imports);

        DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();/*  w w  w  .j  a  va2  s  .  c om*/

        if (!importsInLines.isEmpty()) {
            jTree.setVisible(true);
            String esQueryJson = getESQueryJson(importsInLines);
            String esResultJson = getESResultJson(esQueryJson, esURL + BETTERDOCS_SEARCH);

            if (!esResultJson.equals(EMPTY_ES_URL)) {
                Map<String, String> fileTokensMap = getFileTokens(esResultJson);
                Map<String, ArrayList<CodeInfo>> projectNodes = new HashMap<String, ArrayList<CodeInfo>>();

                updateProjectNodes(imports, fileTokensMap, projectNodes);
                updateRoot(root, projectNodes);

                model.reload(root);
                jTree.addTreeSelectionListener(getTreeSelectionListener(root));
            } else {
                Messages.showInfoMessage(EMPTY_ES_URL, INFO);
            }
        } else {
            jTree.updateUI();
        }
    }
}

From source file:com.compomics.cell_coord.gui.controller.load.LoadTracksController.java

/**
 * Initialize the view components.//from  ww w  .  ja  v a  2s  .  c o  m
 */
private void initView() {
    // create new view
    loadTracksPanel = new LoadTracksPanel();
    // disable the IMPORT FILES button
    loadTracksPanel.getImportFilesButton().setEnabled(false);
    // initialize the flag to keep track of importing
    isImported = false;
    // populate the combobox with available file formats
    // note: these are annoatated as spring beans
    Set<String> parsers = TrackFileParserFactory.getInstance().getParserBeanNames();
    for (String parser : parsers) {
        loadTracksPanel.getFileFormatComboBox().addItem(parser);
    }

    // format the table
    JTableHeader tracksTableHeader = loadTracksPanel.getTracksTable().getTableHeader();
    tracksTableHeader.setBackground(GuiUtils.getHeaderColor());
    tracksTableHeader.setFont(GuiUtils.getHeaderFont());
    tracksTableHeader.setReorderingAllowed(false);

    /**
     * Action Listeners.
     */
    // load directory
    loadTracksPanel.getLoadDirectoryButton().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (directory == null) {
                chooseDirectoryAndLoadData();
            } else {
                // otherwise we ask the user if they want to reload the directory
                Object[] options = { "Load a different directory", "Cancel" };
                int showOptionDialog = JOptionPane.showOptionDialog(null,
                        "It seems a directory was already loaded.\nWhat do you want to do?", "",
                        JOptionPane.CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
                switch (showOptionDialog) {
                case 0: // load a different directory:
                    // reset the model of the directory tree
                    DefaultTreeModel model = (DefaultTreeModel) loadTracksPanel.getDirectoryTree().getModel();
                    DefaultMutableTreeNode rootNote = (DefaultMutableTreeNode) model.getRoot();
                    rootNote.removeAllChildren();
                    model.reload();
                    chooseDirectoryAndLoadData();
                    loadTracksPanel.getChosenDirectoryTextArea().setText(directory.getAbsolutePath());
                    break; // cancel: do nothing
                }
            }
        }
    });

    // import the selected files in the tree
    loadTracksPanel.getImportFilesButton().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // check if an import already took place
            if (!isImported) {
                // get the selected file(s) from the JTree
                TreePath[] selectionPaths = loadTracksPanel.getDirectoryTree().getSelectionPaths();
                if (selectionPaths != null && selectionPaths.length != 0) {
                    // at least a file was selected --  proceed with the import
                    importFiles();
                    isImported = true;
                    cellCoordController.showMessage(selectionPaths.length + " file(s) successfully imported!",
                            "success loading", JOptionPane.INFORMATION_MESSAGE);
                    // do basic computations
                    preprocess();
                    // go to child controllers and show samples in the tables
                    summaryDataController.showSamplesInTable();
                    computationMainController.showSamplesInTable();
                    // proceed with next step in the plugin
                    cellCoordController.getCellCoordFrame().getNextButton().setEnabled(true);
                } else {
                    // inform the user that no file was selected!
                    cellCoordController.showMessage("You have to select at least one file!",
                            "no files selected", JOptionPane.WARNING_MESSAGE);
                }
            } else {
                // an import already took place: ask for user input
                Object[] options = { "Load other file(s)", "Cancel" };
                int showOptionDialog = JOptionPane.showOptionDialog(loadTracksPanel,
                        "It seems some files were already loaded.\nWhat do you want to do?", "",
                        JOptionPane.CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
                switch (showOptionDialog) {
                case 0: // load other files
                    // clear the sample list
                    samples.clear();
                    // clear the track spot list
                    trackSpotsBindingList.clear();
                    // clear the selection in the JTree
                    loadTracksPanel.getDirectoryTree().clearSelection();
                    isImported = false;
                    // inform the user they need to select other files
                    JOptionPane.showMessageDialog(loadTracksPanel, "Please select other files", "",
                            JOptionPane.INFORMATION_MESSAGE);
                    break; // cancel: do nothing
                }
            }

        }
    });

    // add view to parent component
    cellCoordController.getCellCoordFrame().getLoadTracksParentPanel().add(loadTracksPanel, gridBagConstraints);
}

From source file:com.edduarte.protbox.ui.windows.RestoreFileWindow.java

private RestoreFileWindow(final PReg registry) {
    super();/* w  w w .j  a  v  a  2s. co m*/
    setLayout(null);

    final JTextField searchField = new JTextField();
    searchField.setLayout(null);
    searchField.setBounds(2, 2, 301, 26);
    searchField.setBorder(new LineBorder(Color.lightGray));
    searchField.setFont(Constants.FONT);
    add(searchField);

    final JLabel noBackupFilesLabel = new JLabel("<html>No backups files were found!<br><br>"
            + "<font color=\"gray\">If you think there is a problem with the<br>"
            + "backup system, please create an issue here:<br>"
            + "<a href=\"#\">https://github.com/com.edduarte/protbox/issues</a></font></html>");
    noBackupFilesLabel.setLayout(null);
    noBackupFilesLabel.setBounds(20, 50, 300, 300);
    noBackupFilesLabel.setFont(Constants.FONT.deriveFont(14f));
    noBackupFilesLabel.addMouseListener((OnMouseClick) e -> {
        String urlPath = "https://github.com/com.edduarte/protbox/issues";

        try {

            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(new URI(urlPath));

            } else {
                if (SystemUtils.IS_OS_WINDOWS) {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPath);

                } else {
                    java.util.List<String> browsers = Lists.newArrayList("firefox", "opera", "safari",
                            "mozilla", "chrome");

                    for (String browser : browsers) {
                        if (Runtime.getRuntime().exec(new String[] { "which", browser }).waitFor() == 0) {

                            Runtime.getRuntime().exec(new String[] { browser, urlPath });
                            break;
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    });

    DefaultMutableTreeNode rootTreeNode = registry.buildEntryTree();
    final JTree tree = new JTree(rootTreeNode);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    if (rootTreeNode.getChildCount() == 0) {
        searchField.setEnabled(false);
        add(noBackupFilesLabel);
    }
    expandTree(tree);
    tree.setLayout(null);
    tree.setRootVisible(false);
    tree.setEditable(false);
    tree.setCellRenderer(new SearchableTreeCellRenderer(searchField));
    searchField.addKeyListener((OnKeyReleased) e -> {

        // update and expand tree
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.nodeStructureChanged((TreeNode) model.getRoot());
        expandTree(tree);
    });
    final JScrollPane scroll = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setBorder(new DropShadowBorder());
    scroll.setBorder(new LineBorder(Color.lightGray));
    scroll.setBounds(2, 30, 334, 360);
    add(scroll);

    JLabel close = new JLabel(new ImageIcon(Constants.getAsset("close.png")));
    close.setLayout(null);
    close.setBounds(312, 7, 18, 18);
    close.setFont(Constants.FONT);
    close.setForeground(Color.gray);
    close.addMouseListener((OnMouseClick) e -> dispose());
    add(close);

    final JLabel permanentDeleteButton = new JLabel(new ImageIcon(Constants.getAsset("permanent.png")));
    permanentDeleteButton.setLayout(null);
    permanentDeleteButton.setBounds(91, 390, 40, 39);
    permanentDeleteButton.setBackground(Color.black);
    permanentDeleteButton.setEnabled(false);
    permanentDeleteButton.addMouseListener((OnMouseClick) e -> {
        if (permanentDeleteButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();

            if (JOptionPane.showConfirmDialog(null,
                    "Are you sure you wish to permanently delete '" + entry.realName()
                            + "'?\nThis file and its "
                            + "backup copies will be deleted immediately. You cannot undo this action.",
                    "Confirm Cancel", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {

                registry.permanentDelete(entry);
                dispose();
                RestoreFileWindow.getInstance(registry);

            } else {
                setVisible(true);
            }
        }
    });
    add(permanentDeleteButton);

    final JLabel configBackupsButton = new JLabel(new ImageIcon(Constants.getAsset("config.png")));
    configBackupsButton.setLayout(null);
    configBackupsButton.setBounds(134, 390, 40, 39);
    configBackupsButton.setBackground(Color.black);
    configBackupsButton.setEnabled(false);
    configBackupsButton.addMouseListener((OnMouseClick) e -> {
        if (configBackupsButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;

                JFrame frame = new JFrame("Choose backup policy");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below the backup policy for this file:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, PbxFile.BackupPolicy.values(),
                        pbxFile.getBackupPolicy());

                if (option == null) {
                    setVisible(true);
                    return;
                }
                PbxFile.BackupPolicy pickedPolicy = PbxFile.BackupPolicy.valueOf(option.toString());
                pbxFile.setBackupPolicy(pickedPolicy);
            }
            setVisible(true);
        }
    });
    add(configBackupsButton);

    final JLabel restoreBackupButton = new JLabel(new ImageIcon(Constants.getAsset("restore.png")));
    restoreBackupButton.setLayout(null);
    restoreBackupButton.setBounds(3, 390, 85, 39);
    restoreBackupButton.setBackground(Color.black);
    restoreBackupButton.setEnabled(false);
    restoreBackupButton.addMouseListener((OnMouseClick) e -> {
        if (restoreBackupButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFolder) {
                registry.restoreFolderFromEntry((PbxFolder) entry);

            } else if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;
                java.util.List<String> snapshots = pbxFile.snapshotsToString();
                if (snapshots.isEmpty()) {
                    setVisible(true);
                    return;
                }

                JFrame frame = new JFrame("Choose backup");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below what backup snapshot would you like restore:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, snapshots.toArray(), snapshots.get(0));

                if (option == null) {
                    setVisible(true);
                    return;
                }
                int pickedIndex = snapshots.indexOf(option.toString());
                registry.restoreFileFromEntry((PbxFile) entry, pickedIndex);
            }
            dispose();
        }
    });
    add(restoreBackupButton);

    tree.addMouseListener((OnMouseClick) e -> {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (node != null) {
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if ((entry instanceof PbxFolder && entry.areNativeFilesDeleted())) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(false);

            } else if (entry instanceof PbxFile) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(true);

            } else {
                permanentDeleteButton.setEnabled(false);
                restoreBackupButton.setEnabled(false);
                configBackupsButton.setEnabled(false);
            }
        }
    });

    final JLabel cancel = new JLabel(new ImageIcon(Constants.getAsset("cancel.png")));
    cancel.setLayout(null);
    cancel.setBounds(229, 390, 122, 39);
    cancel.setBackground(Color.black);
    cancel.addMouseListener((OnMouseClick) e -> dispose());
    add(cancel);

    addWindowFocusListener(new WindowFocusListener() {
        private boolean gained = false;

        @Override
        public void windowGainedFocus(WindowEvent e) {
            gained = true;
        }

        @Override
        public void windowLostFocus(WindowEvent e) {
            if (gained) {
                dispose();
            }
        }
    });

    setSize(340, 432);
    setUndecorated(true);
    getContentPane().setBackground(Color.white);
    setResizable(false);
    getRootPane().setBorder(BorderFactory.createLineBorder(new Color(100, 100, 100)));
    Utils.setComponentLocationOnCenter(this);
    setVisible(true);
}