Example usage for javax.swing JTree getSelectionPath

List of usage examples for javax.swing JTree getSelectionPath

Introduction

In this page you can find the example usage for javax.swing JTree getSelectionPath.

Prototype

public TreePath getSelectionPath() 

Source Link

Document

Returns the path to the first selected node.

Usage

From source file:MainClass.java

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

    JTree tree = new JTree();
    tree.setRootVisible(true);//from www.  j  a v a  2s . c  o m
    TreeModel model = tree.getModel();
    Object rootObject = model.getRoot();
    if ((rootObject != null) && (rootObject instanceof DefaultMutableTreeNode)) {
        DefaultMutableTreeNode r = (DefaultMutableTreeNode) rootObject;
        printDescendents(r);
        Enumeration breadth = r.breadthFirstEnumeration();
        Enumeration depth = r.depthFirstEnumeration();
        Enumeration preOrder = r.preorderEnumeration();
        printEnumeration(breadth, "Breadth");
        printEnumeration(depth, "Depth");
        printEnumeration(preOrder, "Pre");
    }

    TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
            JTree treeSource = (JTree) treeSelectionEvent.getSource();
            TreePath path = treeSource.getSelectionPath();
            System.out.println(path);
            System.out.println(path.getPath());
            System.out.println(path.getParentPath());
            System.out.println(((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject());
            System.out.println(path.getPathCount());
        }
    };
    tree.addTreeSelectionListener(treeSelectionListener);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 400);
    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);//from  w  w w.j a va  2s .com
    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);//from   ww  w  .  ja  v a 2  s .  com
    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:Main.java

public static void main(String[] args) {
    JFrame f = new JFrame();
    final ConfirmDialog dialog = new ConfirmDialog(f);
    final JTree tree = new JTree();
    tree.setVisibleRowCount(5);//from  www.j  a v  a  2s . co m
    final JScrollPane treeScroll = new JScrollPane(tree);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton b = new JButton("Choose Tree Item");
    b.addActionListener(e -> {
        int result = dialog.showConfirmDialog(treeScroll, "Choose an item");
        if (result == ConfirmDialog.OK_OPTION) {
            System.out.println(tree.getSelectionPath());
        } else {
            System.out.println("User cancelled");
        }
    });
    JPanel p = new JPanel(new BorderLayout());
    p.add(b);
    p.setBorder(new EmptyBorder(50, 50, 50, 50));
    f.setContentPane(p);
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);

}

From source file:Main.java

public static String getNameNodoAtIndex(int ind, JTree jtree) {

    TreePath parentPath = jtree.getSelectionPath();

    int level = 0;

    if (parentPath != null) {

        level = parentPath.getPathCount();
    }//from  w  w  w .  j ava2  s.com

    return "" + parentPath.getPathComponent(ind);
}

From source file:ec.nbdemetra.ui.demo.ComponentsDemo.java

public ComponentsDemo() {
    initStaticResources();/*  w  ww.  ja  va2 s.c  o m*/

    final Map<Id, Component> demoData = lookupComponents();

    final JPanel main = new JPanel(new BorderLayout());
    final JTree tree = new JTree();
    tree.setRootVisible(false);
    tree.setCellRenderer(new IdRenderer(demoData));

    IdsTree.fill(tree, Lists.newArrayList(demoData.keySet()));
    expandAll(tree);

    tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath p = tree.getSelectionPath();
            if (p != null) {
                main.removeAll();
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
                Id id = IdsTree.translate(node);
                Component c = demoData.get(id);
                main.add(c != null ? c : new JPanel());
                main.validate();
                main.repaint();
            }
        }
    });

    JTsList dragDrop = new JTsList();
    dragDrop.setShowHeader(false);
    dragDrop.setInformation(new ITsList.InfoType[] { ITsList.InfoType.TsIdentifier, ITsList.InfoType.Data });
    dragDrop.setPreferredSize(new Dimension(200, 200));
    dragDrop.setTsAction(DemoTsActions.DO_NOTHING);

    JSplitPane left = NbComponents.newJSplitPane(JSplitPane.VERTICAL_SPLIT, NbComponents.newJScrollPane(tree),
            dragDrop);
    JSplitPane splitPane = NbComponents.newJSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, main);
    splitPane.getLeftComponent().setPreferredSize(new Dimension(200, 400));

    setLayout(new BorderLayout());
    add(splitPane, BorderLayout.CENTER);
}

From source file:dataviewer.DataViewer.java

/**
 * Creates new form DataViewer/*w  w  w  .java 2s  .  co m*/
 */
public DataViewer() {
    try {
        for (Enum ee : THREAD.values()) {
            t[ee.ordinal()] = new Thread();
        }
        initComponents();
        DropTarget dropTarget = new DropTarget(tr_files, new DropTargetListenerImpl());
        TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                javax.swing.JTree tree = (javax.swing.JTree) e.getSource();
                TreePath path = tree.getSelectionPath();
                Object[] pnode = (Object[]) path.getPath();
                String name = pnode[pnode.length - 1].toString();
                String ex = getExtension(name);
                if (ex.equals(".txt") || ex.equals(".dat") || ex.equals(".csv") || ex.equals(".tsv")) {
                    selected_file = name;
                } else {
                    selected_file = "";
                }
            }
        };
        tr_files.addTreeSelectionListener(treeSelectionListener);

        tr_files.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() >= 2) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                }
            }
        });

        tr_files.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                    cur_path = (new File(cur_path)).getParent();
                    fill_tree();
                } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                } else if (evt.getKeyCode() == KeyEvent.VK_DELETE) {

                    if (!"".equals(selected_file)) {
                        String name = cur_path + File.separator + selected_file;
                        if ((new File(name)).isFile()) {
                            int dialogResult = JOptionPane.showConfirmDialog(null,
                                    "Selected file [" + selected_file
                                            + "] will be removed and not recoverable.",
                                    "Are you sure?", JOptionPane.YES_NO_OPTION);
                            if (dialogResult == JOptionPane.YES_OPTION) {
                                (new File(name)).delete();
                                fill_tree();
                            }
                        }

                    } else {
                        JOptionPane.showMessageDialog(null,
                                "For safety concern, removing folder is not supported.", "Information",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        tr_files.setCellRenderer(new MyTreeCellRenderer());
        p_count.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

        //tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ctrl1, "tab_read");
        //tp_menu.getActionMap().put("tab_read", (Action) new ActionListenerImpl());
        //tp_menu.setMnemonicAt(0, KeyEvent.VK_1);
        //tp_menu.setMnemonicAt(1, KeyEvent.VK_2);
        /*InputMap inputMap = tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
         ActionMap actionMap = tp_menu.getActionMap();
                
         KeyStroke ctrl1 = KeyStroke.getKeyStroke("ctrl 1");
         inputMap.put(ctrl1, "tab_read");
         actionMap.put("tab_read", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(0);
         }
         });
                
         KeyStroke ctrl2 = KeyStroke.getKeyStroke("ctrl 2");
         inputMap.put(ctrl2, "tab_analyze");
         actionMap.put("tab_analyze", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(1);
         }
         });*/
        config();
    } catch (Exception e) {
        txt_count.setText(e.getMessage());
    }
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

private JPanel createAParameterBox(final boolean first) {

    final JLabel runLabel = new JLabel("<html><b>Number of runs:</b> 0</html>");
    final JLabel warningLabel = new JLabel();

    final JButton closeButton = new JButton();
    closeButton.setOpaque(false);//  ww w . j a v a  2  s  .c o m
    closeButton.setBorder(null);
    closeButton.setFocusable(false);

    if (!first) {
        closeButton.setRolloverIcon(PARAMETER_BOX_REMOVE);
        closeButton.setRolloverEnabled(true);
        closeButton.setIcon(RGBGrayFilter.getDisabledIcon(closeButton, PARAMETER_BOX_REMOVE));
        closeButton.setActionCommand(ACTIONCOMMAND_REMOVE_BOX);
    }

    final JScrollPane treeScrPane = new JScrollPane();
    final DefaultMutableTreeNode treeRoot = new DefaultMutableTreeNode();
    final JTree tree = new JTree(treeRoot);
    ToolTipManager.sharedInstance().registerComponent(tree);

    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setCellRenderer(new ParameterBoxTreeRenderer());
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(final TreeSelectionEvent e) {
            final TreePath selectionPath = tree.getSelectionPath();
            boolean success = true;
            if (editedNode != null
                    && (selectionPath == null || !editedNode.equals(selectionPath.getLastPathComponent())))
                success = modify();

            if (success) {
                if (selectionPath != null) {
                    cancelAllSelectionBut(tree);
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                            .getLastPathComponent();
                    if (!node.equals(editedNode)) {
                        ParameterInATree userObj = null;
                        final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                        if (!node.isRoot()
                                && selectionPath.getPathCount() == model.getPathToRoot(node).length) {
                            userObj = (ParameterInATree) node.getUserObject();
                            final ParameterInfo info = userObj.info;
                            editedNode = node;
                            editedTree = tree;
                            edit(info);
                        } else {
                            tree.setSelectionPath(null);
                            if (cancelButton.isEnabled())
                                cancelButton.doClick();
                            resetSettings();
                            enableDisableSettings(false);
                            editedNode = null;
                            editedTree = null;
                        }

                        updateDescriptionField(userObj);
                    } else
                        updateDescriptionField();

                } else
                    updateDescriptionField();

                enableDisableParameterCombinationButtons();
            } else {
                final DefaultTreeModel model = (DefaultTreeModel) editedTree.getModel();
                final DefaultMutableTreeNode storedEditedNode = editedNode;
                editedNode = null;
                tree.setSelectionPath(null);
                editedNode = storedEditedNode;
                editedTree.setSelectionPath(new TreePath(model.getPathToRoot(editedNode)));
            }
        }
    });

    treeScrPane.setViewportView(tree);
    treeScrPane.setBorder(null);
    treeScrPane.setViewportBorder(null);
    treeScrPane.setPreferredSize(new Dimension(450, 250));

    final JButton upButton = new JButton();
    upButton.setOpaque(false);
    upButton.setRolloverEnabled(true);
    upButton.setIcon(PARAMETER_UP_ICON);
    upButton.setRolloverIcon(PARAMETER_UP_ICON_RO);
    upButton.setDisabledIcon(PARAMETER_UP_ICON_DIS);
    upButton.setBorder(null);
    upButton.setToolTipText("Move up the selected parameter");
    upButton.setActionCommand(ACTIONCOMMAND_MOVE_UP);

    final JButton downButton = new JButton();
    downButton.setOpaque(false);
    downButton.setRolloverEnabled(true);
    downButton.setIcon(PARAMETER_DOWN_ICON);
    downButton.setRolloverIcon(PARAMETER_DOWN_ICON_RO);
    downButton.setDisabledIcon(PARAMETER_DOWN_ICON_DIS);
    downButton.setBorder(null);
    downButton.setToolTipText("Move down the selected parameter");
    downButton.setActionCommand(ACTIONCOMMAND_MOVE_DOWN);

    final JPanel mainPanel = FormsUtils.build("~ f:p:g ~ p ~ r:p",
            "012||" + "333||" + "44_||" + "445||" + "446||" + "44_ f:p:g", runLabel, first ? "" : warningLabel,
            first ? warningLabel : closeButton, new FormsUtils.Separator(""), treeScrPane, upButton, downButton)
            .getPanel();

    mainPanel.setBorder(BorderFactory.createTitledBorder(""));

    final JButton addButton = new JButton();
    addButton.setOpaque(false);
    addButton.setRolloverEnabled(true);
    addButton.setIcon(PARAMETER_ADD_ICON);
    addButton.setRolloverIcon(PARAMETER_ADD_ICON_RO);
    addButton.setDisabledIcon(PARAMETER_ADD_ICON_DIS);
    addButton.setBorder(null);
    addButton.setToolTipText("Add selected parameter");
    addButton.setActionCommand(ACTIONCOMMAND_ADD_PARAM);

    final JButton removeButton = new JButton();
    removeButton.setOpaque(false);
    removeButton.setRolloverEnabled(true);
    removeButton.setIcon(PARAMETER_REMOVE_ICON);
    removeButton.setRolloverIcon(PARAMETER_REMOVE_ICON_RO);
    removeButton.setDisabledIcon(PARAMETER_REMOVE_ICON_DIS);
    removeButton.setBorder(null);
    removeButton.setToolTipText("Remove selected parameter");
    removeButton.setActionCommand(ACTIONCOMMAND_REMOVE_PARAM);

    final JPanel result = FormsUtils.build("p ~ f:p:g", "_0 f:p:g||" + "10 p ||" + "20 p||" + "_0 f:p:g",
            mainPanel, addButton, removeButton).getPanel();

    Style.registerCssClasses(result, Dashboard.CSS_CLASS_COMMON_PANEL);

    final ParameterCombinationGUI pcGUI = new ParameterCombinationGUI(tree, treeRoot, runLabel, warningLabel,
            addButton, removeButton, upButton, downButton);
    parameterTreeBranches.add(pcGUI);

    final ActionListener boxActionListener = new ActionListener() {

        //====================================================================================================
        // methods

        //----------------------------------------------------------------------------------------------------
        public void actionPerformed(final ActionEvent e) {
            final String cmd = e.getActionCommand();

            if (ACTIONCOMMAND_ADD_PARAM.equals(cmd))
                handleAddParameter(pcGUI);
            else if (ACTIONCOMMAND_REMOVE_PARAM.equals(cmd))
                handleRemoveParameter(tree);
            else if (ACTIONCOMMAND_REMOVE_BOX.equals(cmd))
                handleRemoveBox(tree);
            else if (ACTIONCOMMAND_MOVE_UP.equals(cmd))
                handleMoveUp();
            else if (ACTIONCOMMAND_MOVE_DOWN.equals(cmd))
                handleMoveDown();
        }

        //----------------------------------------------------------------------------------------------------
        private void handleAddParameter(final ParameterCombinationGUI pcGUI) {
            final Object[] selectedValues = parameterList.getSelectedValues();
            if (selectedValues != null && selectedValues.length > 0) {
                final AvailableParameter[] params = new AvailableParameter[selectedValues.length];
                System.arraycopy(selectedValues, 0, params, 0, selectedValues.length);
                addParameterToTree(params, pcGUI);
                enableDisableParameterCombinationButtons();
            }
        }

        //----------------------------------------------------------------------------------------------------
        private void handleRemoveParameter(final JTree tree) {
            final TreePath selectionPath = tree.getSelectionPath();
            if (selectionPath != null) {
                cancelButton.doClick();

                final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                        .getLastPathComponent();
                if (!node.isRoot()) {
                    final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent();
                    if (parentNode.isRoot()) {
                        removeParameter(tree, node, parentNode);
                        enableDisableParameterCombinationButtons();
                    }
                }
            }
        }

        //----------------------------------------------------------------------------------------------------
        private void handleRemoveBox(final JTree tree) {
            final int answer = Utilities.askUser(dashboard, false, "Comfirmation",
                    "This operation deletes the combination.",
                    "All related parameter returns back to the list on the left side.", "Are you sure?");
            if (answer == 1) {
                final DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();

                if (tree.getSelectionCount() > 0) {
                    editedNode = null;
                    tree.setSelectionPath(null);
                    if (cancelButton.isEnabled())
                        cancelButton.doClick();
                }

                final DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeModel.getRoot();
                for (int i = 0; i < root.getChildCount(); ++i) {
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
                    removeParameter(tree, node, root);
                }

                enableDisableParameterCombinationButtons();

                parameterTreeBranches.remove(pcGUI);
                combinationsPanel.remove(result);
                combinationsPanel.revalidate();

                updateNumberOfRuns();
            }
        }

        //----------------------------------------------------------------------------------------------------
        private void removeParameter(final JTree tree, final DefaultMutableTreeNode node,
                final DefaultMutableTreeNode parentNode) {
            final ParameterInATree userObj = (ParameterInATree) node.getUserObject();
            final ParameterInfo originalInfo = findOriginalInfo(userObj.info);
            if (originalInfo != null) {
                final DefaultListModel model = (DefaultListModel) parameterList.getModel();
                model.addElement(new AvailableParameter(originalInfo, currentModelHandler.getModelClass()));
                final DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
                treeModel.removeNodeFromParent(node);
                updateNumberOfRuns();
                tree.expandPath(new TreePath(treeModel.getPathToRoot(parentNode)));
            } else
                throw new IllegalStateException(
                        "Parameter " + userObj.info.getName() + " is not found in the model.");
        }

        //----------------------------------------------------------------------------------------------------
        private void handleMoveUp() {
            final TreePath selectionPath = tree.getSelectionPath();
            if (selectionPath != null) {
                boolean success = true;
                if (editedNode != null)
                    success = modify();

                if (success) {
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                            .getLastPathComponent();
                    final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();

                    if (parent == null || parent.getFirstChild().equals(node)) {
                        tree.setSelectionPath(null); // we need this to preserve the state of the parameter settings panel
                        tree.setSelectionPath(new TreePath(node.getPath()));
                        return;
                    }

                    final int index = parent.getIndex(node);
                    final DefaultTreeModel treemodel = (DefaultTreeModel) tree.getModel();
                    treemodel.removeNodeFromParent(node);
                    treemodel.insertNodeInto(node, parent, index - 1);
                    tree.setSelectionPath(new TreePath(node.getPath()));
                }

            }
        }

        //----------------------------------------------------------------------------------------------------
        private void handleMoveDown() {
            final TreePath selectionPath = tree.getSelectionPath();
            if (selectionPath != null) {
                boolean success = true;
                if (editedNode != null)
                    success = modify();

                if (success) {
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                            .getLastPathComponent();
                    final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();

                    if (parent == null || parent.getLastChild().equals(node)) {
                        tree.setSelectionPath(null); // we need this to preserve the state of the parameter settings panel
                        tree.setSelectionPath(new TreePath(node.getPath()));
                        return;
                    }

                    final int index = parent.getIndex(node);
                    final DefaultTreeModel treemodel = (DefaultTreeModel) tree.getModel();
                    treemodel.removeNodeFromParent(node);
                    treemodel.insertNodeInto(node, parent, index + 1);
                    tree.setSelectionPath(new TreePath(node.getPath()));
                }
            }
        }
    };

    GUIUtils.addActionListener(boxActionListener, closeButton, upButton, downButton, addButton, removeButton);

    result.setPreferredSize(new Dimension(500, 250));
    enableDisableParameterCombinationButtons();

    Style.apply(result, dashboard.getCssStyle());

    return result;
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java

private FileSystemObject getSelectedFSO() {
    FileSystemObject fso = null;/* w w w.j  a  v a2 s  . com*/
    JTree tree = getTree(ETreeType.FileSystemTree);
    if (tree.getSelectionPath() != null) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent();
        if (node != null && node.getUserObject() instanceof FileSystemObject) {
            fso = (FileSystemObject) node.getUserObject();
        }
    }
    return fso;
}

From source file:org.languagetool.gui.ConfigurationDialog.java

@NotNull
private MouseAdapter getMouseAdapter() {
    return new MouseAdapter() {
        private void handlePopupEvent(MouseEvent e) {
            JTree tree = (JTree) e.getSource();
            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path == null) {
                return;
            }//from  w w  w .j  a  v  a  2  s .c o m
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            TreePath[] paths = tree.getSelectionPaths();
            boolean isSelected = false;
            if (paths != null) {
                for (TreePath selectionPath : paths) {
                    if (selectionPath.equals(path)) {
                        isSelected = true;
                    }
                }
            }
            if (!isSelected) {
                tree.setSelectionPath(path);
            }
            if (node.isLeaf()) {
                JPopupMenu popup = new JPopupMenu();
                JMenuItem aboutRuleMenuItem = new JMenuItem(messages.getString("guiAboutRuleMenu"));
                aboutRuleMenuItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        RuleNode node = (RuleNode) tree.getSelectionPath().getLastPathComponent();
                        Rule rule = node.getRule();
                        Language lang = config.getLanguage();
                        if (lang == null) {
                            lang = Languages.getLanguageForLocale(Locale.getDefault());
                        }
                        Tools.showRuleInfoDialog(tree, messages.getString("guiAboutRuleTitle"),
                                rule.getDescription(), rule, rule.getUrl(), messages,
                                lang.getShortCodeWithCountryAndVariant());
                    }
                });
                popup.add(aboutRuleMenuItem);
                popup.show(tree, e.getX(), e.getY());
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                handlePopupEvent(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                handlePopupEvent(e);
            }
        }
    };
}