List of usage examples for javax.swing.tree DefaultTreeModel getPathToRoot
public TreeNode[] getPathToRoot(TreeNode aNode)
From source file:Main.java
public Main() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); TreeNode root = getNodes();/* ww w. j a v a2 s. c o m*/ 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); }
From source file:com.sec.ose.osi.ui.frm.main.identification.JTreeAllFiles.java
private TreePath getTreePathByFilePathString(DefaultMutableTreeNode rootNode, String selectedFilePath) { TreePath tp = null;/* ww w.j ava 2 s . co m*/ if (selectedFilePath != null) { DefaultMutableTreeNode node = null; Enumeration<?> enumer = rootNode.breadthFirstEnumeration(); String sFilePath = ""; DefaultTreeModel m_model = new DefaultTreeModel(rootNode); TreeNode[] nodes = null; while (enumer.hasMoreElements()) { node = (DefaultMutableTreeNode) enumer.nextElement(); if (node.getUserObject().equals("/")) continue; sFilePath = ((FileNodeInfo) node.getUserObject()).getFilePath(); if (sFilePath.equals(selectedFilePath)) { nodes = m_model.getPathToRoot(node); tp = new TreePath(nodes); break; } } } return tp; }
From source file:com.SE.myPlayer.MusicPlayerGUI.java
private void folder_Playlist_TreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_folder_Playlist_TreeMouseClicked DefaultMutableTreeNode selectedNode; if (evt.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(evt)) { selectedNode = (DefaultMutableTreeNode) folder_Playlist_Tree.getSelectionPath().getLastPathComponent(); getSongTable(selectedNode.toString()); lastOpen = selectedNode.toString(); for (ObjectBean list1 : list) { if (list1.getTitle().equals("library")) { list1.setLastOpen(lastOpen); }/*from w w w. j ava 2 s . c om*/ } } else if (SwingUtilities.isRightMouseButton(evt)) { DefaultTreeModel myModel = (DefaultTreeModel) folder_Playlist_Tree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) myModel.getRoot(); TreeNode[] nodes = myModel.getPathToRoot(root); TreePath treepath = new TreePath(nodes); folder_Playlist_Tree.setSelectionPath(treepath); folder_Playlist_Tree.scrollPathToVisible(treepath); TreePath path = folder_Playlist_Tree.getPathForLocation(evt.getX(), evt.getY()); folder_Playlist_Tree.setSelectionPath(path); folder_Playlist_Tree.scrollPathToVisible(path); if (!folder_Playlist_Tree.isSelectionEmpty()) { selectedNode = (DefaultMutableTreeNode) folder_Playlist_Tree.getSelectionPath() .getLastPathComponent(); if (!"playlist".equals(selectedNode.toString()) && !"library".equals(selectedNode.toString())) { folderTree_PopUp.show(folder_Playlist_Tree, evt.getX(), evt.getY()); } } } }
From source file:com.SE.myPlayer.MusicPlayerGUI.java
private void createPlaylistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createPlaylistActionPerformed String input = JOptionPane.showInputDialog("Enter playlist Name: "); if (input == null) { } else if (!input.equals("")) { int validInput = sd.newTreeNode(input); if (validInput == 1) { treeReferesh();// ww w . j a v a2 s.c o m DefaultTreeModel model = (DefaultTreeModel) folder_Playlist_Tree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); DefaultMutableTreeNode playlist = (DefaultMutableTreeNode) model.getChild(root, 1); DefaultMutableTreeNode newPlaylist = (DefaultMutableTreeNode) model.getChild(playlist, model.getChildCount(playlist) - 1); getSongTable(newPlaylist.toString()); TreeNode[] nodes = model.getPathToRoot(newPlaylist); TreePath treepath = new TreePath(nodes); folder_Playlist_Tree.setExpandsSelectedPaths(true); folder_Playlist_Tree.setSelectionPath(treepath); folder_Playlist_Tree.scrollPathToVisible(treepath); addJMenuItemsToPopUP(); lastOpen = input; for (ObjectBean list1 : list) { if (list1.getTitle().equals("library")) { list1.setLastOpen(lastOpen); } } } else { createPlaylistActionPerformed(evt); } } else { JOptionPane.showMessageDialog(null, "Please Enter Valid Playlist Name", "Error in Name", JOptionPane.ERROR_MESSAGE); createPlaylistActionPerformed(evt); } }
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);//from ww w . ja 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:eu.crisis_economics.abm.dashboard.Page_Parameters.java
private void addParameterToTree(final AvailableParameter[] parameters, final ParameterCombinationGUI pcGUI) { final DefaultListModel listModel = (DefaultListModel) parameterList.getModel(); final DefaultTreeModel treeModel = (DefaultTreeModel) pcGUI.tree.getModel(); final DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeModel.getRoot(); for (final AvailableParameter parameter : parameters) { listModel.removeElement(parameter); final ParameterInfo selectedInfo = parameter.info; final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode( new ParameterInATree(selectedInfo, currentModelHandler.getModelClass())); treeModel.insertNodeInto(newNode, root, root.getChildCount()); if (selectedInfo instanceof SubmodelInfo) { final SubmodelInfo sInfo = (SubmodelInfo) selectedInfo; if (sInfo.getActualType() != null) { addSubParametersToTree(sInfo, pcGUI.tree, newNode); pcGUI.tree.expandPath(new TreePath(treeModel.getPathToRoot(newNode))); }// w w w. j av a 2s . c om } } updateNumberOfRuns(); pcGUI.tree.expandPath(new TreePath(treeModel.getPathToRoot(root))); }
From source file:com.monead.semantic.workbench.SemanticWorkbench.java
/** * Find a matching individual in the tree. * // w w w. j a va2 s . c o m * @param wrapper * The individual to be matched * @param forward * True to search forward, false to search backward */ private void findMatchingIndividual(Wrapper wrapper, boolean forward) { final DefaultTreeModel treeModel = (DefaultTreeModel) ontModelTree.getModel(); final DefaultMutableTreeNode finalMatchAt; DefaultMutableTreeNode latestMatchAt = null; DefaultMutableTreeNode firstMatchAt = null; boolean foundClickedNode = false; boolean wrappedAroundBackward = false; if (wrapper != null && wrapper instanceof WrapperInstance) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeModel.getRoot(); @SuppressWarnings("unchecked") final Enumeration<DefaultMutableTreeNode> nodeEnumeration = node.preorderEnumeration(); while (nodeEnumeration.hasMoreElements()) { final DefaultMutableTreeNode nextNode = nodeEnumeration.nextElement(); if (nextNode.getUserObject() instanceof Wrapper) { final Wrapper nodeWrapper = (Wrapper) nextNode.getUserObject(); if (wrapper.getUuid().equals(nodeWrapper.getUuid())) { foundClickedNode = true; if (forward) { // If there is one past this location then // use it, otherwise wrap back to top latestMatchAt = null; } else { if (firstMatchAt != null || latestMatchAt != null) { // Searching backward and have found a previous one break; } wrappedAroundBackward = true; } } else if (!wrapper.getUuid().equals(nodeWrapper.getUuid()) && wrapper.getClass().equals(wrapper.getClass()) && wrapper.getLocalName().equals(nodeWrapper.getLocalName()) && wrapper.getUri().equals(nodeWrapper.getUri())) { if (firstMatchAt == null && !foundClickedNode) { // First one found, keep it in case we wrap around firstMatchAt = nextNode; LOGGER.debug("Found first matching node: search UUID: " + wrapper.getUuid() + " found UUID: " + nodeWrapper.getUuid()); } else { // Keep track of latest one found latestMatchAt = nextNode; LOGGER.debug("Found a following matching node: search UUID: " + wrapper.getUuid() + " found UUID: " + nodeWrapper.getUuid()); // If going forward then this is the next match if (forward && foundClickedNode) { break; } } } } } if ((!forward || foundClickedNode) && latestMatchAt != null) { finalMatchAt = latestMatchAt; if (forward) { setStatus("Next " + wrapper.getLocalName() + " found"); } else { if (wrappedAroundBackward) { setStatus("Wrapped to bottom of tree and found a " + wrapper.getLocalName()); } else { setStatus("Previous " + wrapper.getLocalName() + " found"); } } } else if (firstMatchAt != null) { finalMatchAt = firstMatchAt; if (forward) { setStatus("Wrapped to top of tree and found a " + wrapper.getLocalName()); } else { setStatus("Previous " + wrapper.getLocalName() + " found"); } } else { finalMatchAt = null; setStatus(wrapper.getLocalName() + " could not be found elsewhere in the tree"); } if (finalMatchAt != null) { ontModelTree.setExpandsSelectedPaths(true); // Scroll to the selected node SwingUtilities.invokeLater(new Runnable() { public void run() { ontModelTree.setSelectionPath(new TreePath(treeModel.getPathToRoot(finalMatchAt))); ontModelTree.scrollPathToVisible(new TreePath(treeModel.getPathToRoot(finalMatchAt))); final Rectangle visible = ontModelTree.getVisibleRect(); visible.x = 0; ontModelTree.scrollRectToVisible(visible); } }); } } }
From source file:net.sourceforge.squirrel_sql.client.gui.HelpViewerWindow.java
private void selectTreeNodeForURL(URL url) { // Strip local part of URL. String key = url.toString();//from w w w .j av a 2 s . c om final int idx = key.lastIndexOf('#'); if (idx > -1) { key = key.substring(0, idx); } DefaultMutableTreeNode node = _nodes.get(key); if (node != null) // && node != _tree.getLastSelectedPathComponent()) { DefaultTreeModel model = (DefaultTreeModel) _tree.getModel(); TreePath path = new TreePath(model.getPathToRoot(node)); if (path != null) { _tree.expandPath(path); _tree.scrollPathToVisible(path); _tree.setSelectionPath(path); } } }