Example usage for javax.swing.tree TreePath getLastPathComponent

List of usage examples for javax.swing.tree TreePath getLastPathComponent

Introduction

In this page you can find the example usage for javax.swing.tree TreePath getLastPathComponent.

Prototype

public Object getLastPathComponent() 

Source Link

Document

Returns the last element of this path.

Usage

From source file:GenealogyExample.java

/**
 * Get the selected item in the tree, and call showAncestor with this item on
 * the model./*from  w  w w .j av  a  2 s .  c om*/
 */
public void showAncestor(boolean b) {
    Object newRoot = null;
    TreePath path = getSelectionModel().getSelectionPath();
    if (path != null) {
        newRoot = path.getLastPathComponent();
    }
    ((GenealogyModel) getModel()).showAncestor(b, newRoot);
}

From source file:de.codesourcery.eve.skills.ui.components.impl.ItemBrowserComponent.java

@Override
protected JPanel createPanel() {

    final JPanel result = new JPanel();
    result.setLayout(new GridBagLayout());

    treeModelBuilder = new MarketGroupTreeModelBuilder(dataModel);

    treeModelBuilder.attach(itemTree);/*from   w w  w  . jav  a2  s .  com*/

    itemTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            if (e.getPath() != null) {
                treeSelectionChanged((ITreeNode) e.getPath().getLastPathComponent());
            } else {
                treeSelectionChanged(null);
            }
        }
    });

    itemTree.setCellRenderer(new DefaultTreeCellRenderer() {
        public java.awt.Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            final ITreeNode node = (ITreeNode) value;
            if (node.getValue() instanceof MarketGroup) {
                setText(((MarketGroup) node.getValue()).getName());
            } else if (node.getValue() instanceof InventoryType) {
                setText(((InventoryType) node.getValue()).getName());
            }
            return this;
        };
    });

    // text area
    itemDetails.setLineWrap(true);
    itemDetails.setWrapStyleWord(true);
    itemDetails.setEditable(false);

    // context menu
    final PopupMenuBuilder menuBuilder = new PopupMenuBuilder();
    menuBuilder.addItem("Refine...", new AbstractAction() {

        @Override
        public boolean isEnabled() {
            return getSelectedType() != null && selectionProvider.getSelectedItem() != null;
        }

        private InventoryType getSelectedType() {
            final TreePath selection = itemTree.getSelectionPath();
            if (selection != null && selection.getPathCount() > 0) {
                final ITreeNode node = (ITreeNode) selection.getLastPathComponent();
                if (node.getValue() instanceof InventoryType) {
                    return (InventoryType) node.getValue();
                }
            }
            return null;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            final ICharacter currentCharacter = selectionProvider.getSelectedItem();
            final InventoryType t = getSelectedType();
            if (t != null && currentCharacter != null) {

                final RefiningComponent comp = new RefiningComponent(currentCharacter);
                comp.setModal(true);
                comp.setItemsToRefine(Collections.singletonList(new ItemWithQuantity(getSelectedType(), 1)));
                ComponentWrapper.wrapComponent(comp).setVisible(true);
            }

        }
    });
    menuBuilder.attach(itemTree);

    result.add(new JScrollPane(itemTree), constraints(0, 0).resizeBoth().end());
    result.add(new JScrollPane(itemDetails), constraints(1, 0).resizeBoth().end());
    return result;
}

From source file:uk.co.markfrimston.tasktree.Main.java

protected DefaultMutableTreeNode getSelectedNode() {
    int[] selected = tree.getSelectionRows();
    if (selected == null || selected.length == 0) {
        return null;
    }//from   w ww.  j a  v a 2 s. c o  m
    TreePath path = tree.getPathForRow(selected[0]);
    if (path == null || path.getPathCount() == 0) {
        return null;
    }
    return (DefaultMutableTreeNode) path.getLastPathComponent();
}

From source file:guineu.modules.database.openQualityControlFileDB.DatasetOpenDialog.java

private void deleteButtonActionPerformed(ActionEvent evt) {
    List<Integer> tobeRemoved = new ArrayList<Integer>();
    if (tree != null) {
        for (int index = 0; index < tree.getRowCount(); index++) {
            TreePath path = tree.getPathForRow(index);
            if (path != null) {
                CheckNode node = (CheckNode) path.getLastPathComponent();
                if (node.isSelected) {
                    deleteDataset(node);
                    tobeRemoved.add(index);
                }//from   w ww .  j a  v  a2 s .  co m
            }
        }
    }
    this.exitCode = ExitCode.CANCEL;
    dispose();
}

From source file:guineu.modules.database.openQualityControlFileDB.DatasetOpenDialog.java

/**
 * Creates selected datasets/*from ww w. j a  va 2s . c o  m*/
 * @param evt
 */
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
    if (tree != null) {
        for (int index = 0; index < tree.getRowCount(); index++) {
            TreePath path = tree.getPathForRow(index);
            if (path != null) {
                CheckNode node = (CheckNode) path.getLastPathComponent();
                if (node.isSelected) {
                    createDataset(node);
                }
            }
        }
    }

    exitCode = ExitCode.OK;
    dispose();
}

From source file:gov.sandia.umf.platform.ui.jobs.RunPanel.java

public void delete() {
    TreePath[] paths = tree.getSelectionPaths();
    if (paths.length < 1)
        return;/* w w  w  .jav  a 2s  . c  om*/

    boolean nextSelectionIsParent = false;
    NodeBase firstSelection = (NodeBase) paths[0].getLastPathComponent();
    NodeBase lastSelection = (NodeBase) paths[paths.length - 1].getLastPathComponent();
    NodeBase nextSelection = (NodeBase) lastSelection.getNextSibling();
    if (nextSelection == null)
        nextSelection = (NodeBase) firstSelection.getPreviousSibling();
    if (nextSelection == null) {
        nextSelection = (NodeBase) firstSelection.getParent();
        nextSelectionIsParent = true;
    }

    for (TreePath path : paths) {
        final NodeBase node = (NodeBase) path.getLastPathComponent();
        model.removeNodeFromParent(node);
        if (displayNode == node) {
            synchronized (displayText) {
                displayText.setText("");
            }
            if (displayPane.getViewport().getView() != displayText)
                displayPane.setViewportView(displayText);
        }

        new Thread("RunPanel Delete") {
            public void run() {
                if (node instanceof NodeJob) {
                    NodeJob job = (NodeJob) node;
                    synchronized (running) {
                        running.remove(job);
                    }

                    MDoc doc = (MDoc) job.source;
                    ExecutionEnv env = ExecutionEnv.factory(doc.getOrDefault("localhost", "$metadata", "host"));
                    String jobName = doc.key();
                    try {
                        env.deleteJob(jobName);
                    } // TODO: Also terminate execution, if possible.
                    catch (Exception e) {
                    }

                    doc.delete();
                } else if (node instanceof NodeFile) {
                    ((NodeFile) node).path.delete();
                }
            };
        }.start();
    }

    if (nextSelectionIsParent) {
        if (nextSelection.getChildCount() > 0)
            tree.setSelectionPath(new TreePath(((NodeBase) nextSelection.getChildAt(0)).getPath()));
        else if (nextSelection != root)
            tree.setSelectionPath(new TreePath(nextSelection.getPath()));
    } else {
        tree.setSelectionPath(new TreePath(nextSelection.getPath()));
    }
}

From source file:Main.java

public Main() {
    setLayout(new GridLayout(1, 3));
    tree = new JTree(getTreeModel());
    tree.setDragEnabled(true);//from   w  w w .  j  a  v a  2s . c o  m
    tree.setPreferredSize(new Dimension(200, 400));
    JScrollPane scroll = new JScrollPane();
    scroll.setViewportView(tree);

    treeModel = getTreeModel();
    JTree secondTree = new JTree(treeModel);
    secondTree.setPreferredSize(new Dimension(200, 400));
    secondTree.setTransferHandler(new TransferHandler() {
        @Override
        public boolean importData(TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }
            JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation();
            TreePath path = dl.getPath();
            int childIndex = dl.getChildIndex();

            String data;
            try {
                data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }
            if (childIndex == -1) {
                childIndex = tree.getModel().getChildCount(path.getLastPathComponent());
            }

            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(data);
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            treeModel.insertNodeInto(newNode, parentNode, childIndex);

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

        public boolean canImport(TransferSupport support) {
            if (!support.isDrop()) {
                return false;
            }
            support.setShowDropLocation(true);
            if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                System.out.println("only string is supported");
                return false;
            }
            JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation();
            TreePath path = dl.getPath();
            if (path == null) {
                return false;
            }
            return true;
        }
    });
    JScrollPane secondScroll = new JScrollPane();
    secondScroll.setViewportView(secondTree);

    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.add(scroll, BorderLayout.CENTER);
    JPanel btmPanel = new JPanel(new BorderLayout());
    btmPanel.add(secondScroll, BorderLayout.CENTER);

    add(topPanel);
    add(btmPanel);
}

From source file:com.igormaznitsa.sciareto.ui.tree.ExplorerTree.java

public ExplorerTree(@Nonnull final Context context) {
      super();//from   www. j  a v a 2  s .c  o m
      this.projectTree = new DnDTree();
      this.context = context;
      this.projectTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
      this.projectTree.setDropMode(DropMode.ON);

      this.projectTree.setEditable(true);

      ToolTipManager.sharedInstance().registerComponent(this.projectTree);

      this.projectTree.setCellRenderer(new TreeCellRenderer());
      this.projectTree.setModel(new NodeProjectGroup(context, "."));
      this.projectTree.setRootVisible(false);
      this.setViewportView(this.projectTree);

      this.projectTree.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(@Nonnull final MouseEvent e) {
              if (e.getClickCount() > 1) {
                  final int selRow = projectTree.getRowForLocation(e.getX(), e.getY());
                  final TreePath selPath = projectTree.getPathForLocation(e.getX(), e.getY());
                  if (selRow >= 0) {
                      final NodeFileOrFolder node = (NodeFileOrFolder) selPath.getLastPathComponent();
                      if (node != null && node.isLeaf()) {
                          final File file = node.makeFileForNode();
                          if (file != null && !context.openFileAsTab(file)) {
                              UiUtils.openInSystemViewer(file);
                          }
                      }
                  }
              }
          }

          @Override
          public void mouseReleased(@Nonnull final MouseEvent e) {
              if (e.isPopupTrigger()) {
                  processPopup(e);
              }
          }

          @Override
          public void mousePressed(@Nonnull final MouseEvent e) {
              if (e.isPopupTrigger()) {
                  processPopup(e);
              }
          }

          private void processPopup(@Nonnull final MouseEvent e) {
              final TreePath selPath = projectTree.getPathForLocation(e.getX(), e.getY());
              if (selPath != null) {
                  projectTree.setSelectionPath(selPath);
                  final Object last = selPath.getLastPathComponent();
                  if (last instanceof NodeFileOrFolder) {
                      makePopupMenu((NodeFileOrFolder) last).show(e.getComponent(), e.getX(), e.getY());
                  }
              }
          }

      });
  }

From source file:net.sf.mzmine.desktop.impl.projecttree.ProjectTreeMouseHandler.java

private void handlePopupTriggerEvent(MouseEvent e) {
    TreePath clickedPath = tree.getPathForLocation(e.getX(), e.getY());
    if (clickedPath == null)
        return;//w  ww.  j  a  v  a  2s . co  m
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) clickedPath.getLastPathComponent();
    Object clickedObject = node.getUserObject();

    if (clickedObject instanceof RawDataFile)
        dataFilePopupMenu.show(e.getComponent(), e.getX(), e.getY());
    if (clickedObject instanceof Scan)
        scanPopupMenu.show(e.getComponent(), e.getX(), e.getY());
    if (clickedObject instanceof MassList)
        massListPopupMenu.show(e.getComponent(), e.getX(), e.getY());
    if (clickedObject instanceof PeakList)
        peakListPopupMenu.show(e.getComponent(), e.getX(), e.getY());
    if (clickedObject instanceof PeakListRow)
        peakListRowPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}

From source file:it.unibas.spicygui.controllo.datasource.operators.CreaWidgetAlberi.java

private void createWidget(Point point, JTree albero, TreePath treePath, boolean sourceFlag) {
    Point punto = null;//from w ww. ja  v a 2 s  .  c o m
    TreeNode treeNode = (TreeNode) treePath.getLastPathComponent();
    TreeNodeAdapter nodeAdapter = (TreeNodeAdapter) ((DefaultMutableTreeNode) treeNode).getUserObject();
    INode iNode = nodeAdapter.getINode();
    if (sourceFlag) {
        VMDPinWidgetSource pin = new VMDPinWidgetSource(scene);
        settaWidgetAlbero(pin, sourceFlag);
        int width = albero.getPathBounds(treePath).width;
        int height = albero.getPathBounds(treePath).height;
        if (logger.isTraceEnabled()) {
            logger.trace("width: " + width + " height: " + height);
        }

        punto = new Point(point.x + (width - Costanti.OFFSET_X_WIDGET_SOURCE),
                point.y + (height / Costanti.OFFSET_Y_WIDGET_SOURCE));
        pin.setPreferredLocation(punto);
        pin.getActions().addAction(ActionFactory.createConnectAction(connectionLayer,
                new ActionSceneConnection(scene, connectionLayer, mainLayer, this.correspondencesCreator)));
        mainLayer.addChild(pin,
                new CaratteristicheWidgetTree(albero, point, treePath, Costanti.TREE_SOURCE, width, iNode));
        iNode.addAnnotation(pinWidgetTreeConstant, pin);
        //TODO Da togliere l'ultima condizione nel momento in cui le tgd possano tracciare corrispondenze
        if ((iNode.isExcluded()) || !(iNode instanceof AttributeNode)
                || (pinWidgetTreeConstant.equals(Costanti.PIN_WIDGET_TREE_TGD))) {
            pin.setEnabled(false);
        }

    } else {
        VMDPinWidgetTarget pin = new VMDPinWidgetTarget(scene);
        settaWidgetAlbero(pin, sourceFlag);
        punto = new Point(point.x, point.y + 5);
        pin.setPreferredLocation(punto);
        pin.getActions().addAction(
                ActionFactory.createConnectAction(connectionLayer, new ActionSceneConnectionTarget(scene,
                        connectionLayer, mainLayer, this.correspondencesCreator)));
        mainLayer.addChild(pin,
                new CaratteristicheWidgetTree(albero, point, treePath, Costanti.TREE_TARGET, 0, iNode));
        iNode.addAnnotation(pinWidgetTreeConstant, pin);
        //TODO Da togliere l'ultima condizione nel momento in cui le tgd possano tracciare corrispondenze
        if ((iNode.isExcluded()) || !(iNode instanceof AttributeNode)
                || (pinWidgetTreeConstant.equals(Costanti.PIN_WIDGET_TREE_TGD))) {
            pin.setEnabled(false);
        }

    }
    scene.validate();
}