Example usage for javax.swing JTree getSelectionPaths

List of usage examples for javax.swing JTree getSelectionPaths

Introduction

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

Prototype

public TreePath[] getSelectionPaths() 

Source Link

Document

Returns the paths of all selected values.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JTree tree = new JTree();

    JFrame f = new JFrame();
    f.add(new JScrollPane(tree));
    f.setSize(300, 300);//www . j a  v  a  2 s .c  o  m
    f.setVisible(true);

    // Get paths of all selected nodes
    TreePath[] paths = tree.getSelectionPaths();

}

From source file:Main.java

private void myPopupEvent(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    JTree tree = (JTree) e.getSource();
    TreePath path = tree.getPathForLocation(x, y);
    if (path == null)
        return;//from ww w.j  av  a  2 s  . com

    DefaultMutableTreeNode rightClickedNode = (DefaultMutableTreeNode) path.getLastPathComponent();

    TreePath[] selectionPaths = tree.getSelectionPaths();

    boolean isSelected = false;
    if (selectionPaths != null) {
        for (TreePath selectionPath : selectionPaths) {
            if (selectionPath.equals(path)) {
                isSelected = true;
            }
        }
    }
    if (!isSelected) {
        tree.setSelectionPath(path);
    }
    if (rightClickedNode.isLeaf()) {
        JPopupMenu popup = new JPopupMenu();
        final JMenuItem refreshMenuItem = new JMenuItem("refresh");
        refreshMenuItem.addActionListener(ev -> System.out.println("refresh!"));
        popup.add(refreshMenuItem);
        popup.show(tree, x, y);
    }
}

From source file:Main.java

public Main() {
    super(BoxLayout.Y_AXIS);
    glassPane.setOpaque(false);//from  w  ww .j  a v a2 s  .co  m
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    for (int i = 0; i < 14000; i++) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode("Root" + i);
        node.add(new DefaultMutableTreeNode("Child" + i));
        root.add(node);
    }

    final JTree tree = new JTree(root);
    tree.setRootVisible(false);
    final JScrollPane pane = new JScrollPane(tree);
    add(pane);

    JButton button = new JButton("Expand");
    button.addActionListener(e -> {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                TreePath[] paths = tree.getSelectionPaths();
                if (paths == null || paths.length == 0) {
                    glassPane.setVisible(false);
                    return;
                }
                tree.setSelectionPath(paths[0]);

                for (int i = 0; i < paths.length; i++) {
                    tree.expandPath(paths[i]);
                }
                glassPane.setVisible(false);
            }
        });
        getRootPane().setGlassPane(glassPane);
        glassPane.setVisible(true);
        t.start();
    });
    add(button);
    glassPane.addMouseWheelListener(e -> {
        for (MouseWheelListener mwl : pane.getMouseWheelListeners()) {
            mwl.mouseWheelMoved(e);
        }
    });
}

From source file:cool.pandora.modeller.ui.jpanel.base.BagView.java

/**
 * registerTreeListener./*w w w .  j  a v  a 2s .  c o m*/
 *
 * @param label String
 * @param tree  JTree
 */
public void registerTreeListener(final String label, final JTree tree) {
    if (AbstractBagConstants.DATA_DIRECTORY.equals(label)) {
        tree.addTreeSelectionListener(e -> {

            final TreePath[] paths = tree.getSelectionPaths();
            if (paths == null || paths.length == 0) {
                return;
            }

            for (final TreePath path : paths) {
                if (path.getPathCount() == 1) {
                    removeDataToolBarAction.setEnabled(false);
                    return;
                }
            }

            removeDataToolBarAction.setEnabled(true);
        });
    } else {
        tree.addTreeSelectionListener(e -> {

            final TreePath[] paths = tree.getSelectionPaths();
            if (paths == null || paths.length == 0) {
                return;
            }

            for (final TreePath path : paths) {
                if (path.getPathCount() == 1) {
                    removeTagFileToolbarAction.setEnabled(false);
                    return;
                }
            }

            removeTagFileToolbarAction.setEnabled(true);
        });
    }
}

From source file:com.t3.client.ui.T3Frame.java

private JComponent createTokenTreePanel() {
    final JTree tree = new JTree();
    tokenPanelTreeModel = new TokenPanelTreeModel(tree);
    tree.setModel(tokenPanelTreeModel);//from  www  . j  av  a  2 s. com
    tree.setCellRenderer(new TokenPanelTreeCellRenderer());
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.addMouseListener(new MouseAdapter() {
        // TODO: Make this a handler class, not an aic
        @Override
        public void mousePressed(MouseEvent e) {
            // tree.setSelectionPath(tree.getPathForLocation(e.getX(), e.getY()));
            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path == null) {
                return;
            }
            Object row = path.getLastPathComponent();
            int rowIndex = tree.getRowForLocation(e.getX(), e.getY());
            if (SwingUtilities.isLeftMouseButton(e)) {
                if (!SwingUtil.isShiftDown(e)) {
                    tree.clearSelection();
                }
                tree.addSelectionInterval(rowIndex, rowIndex);

                if (row instanceof Token) {
                    if (e.getClickCount() == 2) {
                        Token token = (Token) row;
                        getCurrentZoneRenderer().clearSelectedTokens();
                        getCurrentZoneRenderer().centerOn(new ZonePoint(token.getX(), token.getY()));

                        // Pick an appropriate tool
                        getToolbox().setSelectedTool(token.isToken() ? PointerTool.class : StampTool.class);
                        getCurrentZoneRenderer().setActiveLayer(token.getLayer());
                        getCurrentZoneRenderer().selectToken(token.getId());
                        getCurrentZoneRenderer().requestFocusInWindow();
                    }
                }
            }
            if (SwingUtilities.isRightMouseButton(e)) {
                if (!isRowSelected(tree.getSelectionRows(), rowIndex) && !SwingUtil.isShiftDown(e)) {
                    tree.clearSelection();
                    tree.addSelectionInterval(rowIndex, rowIndex);
                }
                final int x = e.getX();
                final int y = e.getY();
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        Token firstToken = null;
                        Set<GUID> selectedTokenSet = new HashSet<GUID>();
                        for (TreePath path : tree.getSelectionPaths()) {
                            if (path.getLastPathComponent() instanceof Token) {
                                Token token = (Token) path.getLastPathComponent();
                                if (firstToken == null) {
                                    firstToken = token;
                                }
                                if (AppUtil.playerOwns(token)) {
                                    selectedTokenSet.add(token.getId());
                                }
                            }
                        }
                        if (!selectedTokenSet.isEmpty()) {
                            try {
                                if (firstToken.isStamp()) {
                                    new StampPopupMenu(selectedTokenSet, x, y, getCurrentZoneRenderer(),
                                            firstToken).showPopup(tree);
                                } else {
                                    new TokenPopupMenu(selectedTokenSet, x, y, getCurrentZoneRenderer(),
                                            firstToken).showPopup(tree);
                                }
                            } catch (IllegalComponentStateException icse) {
                                log.info(tree.toString(), icse);
                            }
                        }
                    }
                });
            }
        }
    });
    TabletopTool.getEventDispatcher().addListener(new AppEventListener() {
        @Override
        public void handleAppEvent(AppEvent event) {
            tokenPanelTreeModel.setZone((Zone) event.getNewValue());
        }
    }, TabletopTool.ZoneEvent.Activated);
    return tree;
}

From source file:net.rptools.maptool.client.ui.MapToolFrame.java

private JComponent createTokenTreePanel() {
    final JTree tree = new JTree();
    tokenPanelTreeModel = new TokenPanelTreeModel(tree);
    tree.setModel(tokenPanelTreeModel);/* w w  w  .  j av a  2s. com*/
    tree.setCellRenderer(new TokenPanelTreeCellRenderer());
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.addMouseListener(new MouseAdapter() {
        // TODO: Make this a handler class, not an aic
        @Override
        public void mousePressed(MouseEvent e) {
            // tree.setSelectionPath(tree.getPathForLocation(e.getX(), e.getY()));
            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path == null) {
                return;
            }
            Object row = path.getLastPathComponent();
            int rowIndex = tree.getRowForLocation(e.getX(), e.getY());
            if (SwingUtilities.isLeftMouseButton(e)) {
                if (!SwingUtil.isShiftDown(e) && !SwingUtil.isControlDown(e)) {
                    tree.clearSelection();
                }
                tree.addSelectionInterval(rowIndex, rowIndex);

                if (row instanceof Token) {
                    if (e.getClickCount() == 2) {
                        Token token = (Token) row;
                        getCurrentZoneRenderer().clearSelectedTokens();
                        getCurrentZoneRenderer().centerOn(new ZonePoint(token.getX(), token.getY()));

                        // Pick an appropriate tool
                        getToolbox().setSelectedTool(token.isToken() ? PointerTool.class : StampTool.class);
                        getCurrentZoneRenderer().setActiveLayer(token.getLayer());
                        getCurrentZoneRenderer().selectToken(token.getId());
                        getCurrentZoneRenderer().requestFocusInWindow();
                    }
                }
            }
            if (SwingUtilities.isRightMouseButton(e)) {
                if (!isRowSelected(tree.getSelectionRows(), rowIndex) && !SwingUtil.isShiftDown(e)) {
                    tree.clearSelection();
                    tree.addSelectionInterval(rowIndex, rowIndex);
                }
                final int x = e.getX();
                final int y = e.getY();
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        Token firstToken = null;
                        Set<GUID> selectedTokenSet = new HashSet<GUID>();
                        for (TreePath path : tree.getSelectionPaths()) {
                            if (path.getLastPathComponent() instanceof Token) {
                                Token token = (Token) path.getLastPathComponent();
                                if (firstToken == null) {
                                    firstToken = token;
                                }
                                if (AppUtil.playerOwns(token)) {
                                    selectedTokenSet.add(token.getId());
                                }
                            }
                        }
                        if (!selectedTokenSet.isEmpty()) {
                            try {
                                if (firstToken.isStamp()) {
                                    new StampPopupMenu(selectedTokenSet, x, y, getCurrentZoneRenderer(),
                                            firstToken).showPopup(tree);
                                } else {
                                    new TokenPopupMenu(selectedTokenSet, x, y, getCurrentZoneRenderer(),
                                            firstToken).showPopup(tree);
                                }
                            } catch (IllegalComponentStateException icse) {
                                log.info(tree.toString(), icse);
                            }
                        }
                    }
                });
            }
        }
    });
    MapTool.getEventDispatcher().addListener(new AppEventListener() {
        public void handleAppEvent(AppEvent event) {
            tokenPanelTreeModel.setZone((Zone) event.getNewValue());
        }
    }, MapTool.ZoneEvent.Activated);
    return tree;
}

From source file:net.rptools.maptool.client.ui.MapToolFrame.java

private JComponent createDrawTreePanel() {
    final JTree tree = new JTree();
    drawablesPanel = new DrawablesPanel();
    drawPanelTreeModel = new DrawPanelTreeModel(tree);
    tree.setModel(drawPanelTreeModel);//from ww  w  . j  a v  a2s.  c o m
    tree.setCellRenderer(new DrawPanelTreeCellRenderer());
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setContinuousLayout(true);

    splitPane.setTopComponent(new JScrollPane(tree));
    splitPane.setBottomComponent(drawablesPanel);
    splitPane.setDividerLocation(100);
    // Add mouse Event for right click menu
    tree.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path == null) {
                return;
            }
            Object row = path.getLastPathComponent();
            int rowIndex = tree.getRowForLocation(e.getX(), e.getY());
            if (SwingUtilities.isLeftMouseButton(e)) {
                if (!SwingUtil.isShiftDown(e) && !SwingUtil.isControlDown(e)) {
                    tree.clearSelection();
                }
                tree.addSelectionInterval(rowIndex, rowIndex);
                if (row instanceof DrawnElement) {
                    if (e.getClickCount() == 2) {
                        DrawnElement de = (DrawnElement) row;
                        getCurrentZoneRenderer()
                                .centerOn(new ZonePoint((int) de.getDrawable().getBounds().getCenterX(),
                                        (int) de.getDrawable().getBounds().getCenterY()));
                    }
                }

                int[] treeRows = tree.getSelectionRows();
                java.util.Arrays.sort(treeRows);
                drawablesPanel.clearSelectedIds();
                for (int i = 0; i < treeRows.length; i++) {
                    TreePath p = tree.getPathForRow(treeRows[i]);
                    if (p.getLastPathComponent() instanceof DrawnElement) {
                        DrawnElement de = (DrawnElement) p.getLastPathComponent();
                        drawablesPanel.addSelectedId(de.getDrawable().getId());
                    }
                }
            }
            if (SwingUtilities.isRightMouseButton(e)) {
                if (!isRowSelected(tree.getSelectionRows(), rowIndex) && !SwingUtil.isShiftDown(e)) {
                    tree.clearSelection();
                    tree.addSelectionInterval(rowIndex, rowIndex);
                    drawablesPanel.clearSelectedIds();
                }
                final int x = e.getX();
                final int y = e.getY();
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        DrawnElement firstElement = null;
                        Set<GUID> selectedDrawSet = new HashSet<GUID>();
                        for (TreePath path : tree.getSelectionPaths()) {
                            if (path.getLastPathComponent() instanceof DrawnElement) {
                                DrawnElement de = (DrawnElement) path.getLastPathComponent();
                                if (firstElement == null) {
                                    firstElement = de;
                                }
                                selectedDrawSet.add(de.getDrawable().getId());
                            }
                        }
                        if (!selectedDrawSet.isEmpty()) {
                            try {
                                new DrawPanelPopupMenu(selectedDrawSet, x, y, getCurrentZoneRenderer(),
                                        firstElement).showPopup(tree);
                            } catch (IllegalComponentStateException icse) {
                                log.info(tree.toString(), icse);
                            }
                        }
                    }
                });
            }
        }

    });
    // Add Zone Change event
    MapTool.getEventDispatcher().addListener(new AppEventListener() {
        public void handleAppEvent(AppEvent event) {
            drawPanelTreeModel.setZone((Zone) event.getNewValue());
        }
    }, MapTool.ZoneEvent.Activated);
    return splitPane;
}

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

public void createAutoStructItem(boolean fromSingleFile) {
    if (canCreateAutoStructItem()) {
        JTree tree = getTree(ETreeType.EntityTree);
        if ((tree != null) && (tree.getSelectionCount() > 0)) {
            String structNodeName = getNewStructNodeName();
            if (structNodeName == null) {
                return;
            }/* w ww  .  j  a v a 2s  .  c  o m*/
            StructMapCollection structure = getStructures();
            FSOCollection files = new FSOCollection();
            if (fromSingleFile) {
                // Complex one - need to recurse through tree & get all
                // matching files
                TreePath[] paths = tree.getSelectionPaths();
                DefaultMutableTreeNode nodeSource = null;
                for (int i = 0; i < paths.length; i++) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
                    if (node.getUserObject() instanceof FileSystemObject) {
                        nodeSource = node;
                        break;
                    }
                }
                if (nodeSource != null) {
                    DepositTreeModel model = (DepositTreeModel) tree.getModel();
                    DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) model.getRoot();
                    FileSystemObject fso = (FileSystemObject) nodeSource.getUserObject();
                    String baseFileName = fso.getFileNameWithoutRepTypeOrSuffix();
                    getMatchingFiles(baseFileName, rootNode, files);
                }
            } else {
                TreePath[] paths = tree.getSelectionPaths();
                for (int i = 0; i < paths.length; i++) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
                    if (node.getUserObject() instanceof FileSystemObject) {
                        FileSystemObject fso = (FileSystemObject) node.getUserObject();
                        files.add(fso);
                    }
                }
            }

            files.setSortBy(manualDepositFrame.getCurrentSortBy());
            files.reSortList();
            int structSortOrder = 0;
            for (FileSystemObject fso : files) {
                fso.setStructSortOrder(structSortOrder);
                structSortOrder++;
            }
            StructMap map = StructMap.create(structNodeName, null, files, 0);
            structure.add(map);
            addStructMap(structure);
        }
    }
}

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

public boolean canDeleteEntityItem() {
    boolean canDelete = false;
    JTree tree = theEntityTree;
    if (tree != null) {
        if (tree.getSelectionCount() > 0) {
            TreePath[] paths = tree.getSelectionPaths();
            for (int i = 0; i < paths.length; i++) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
                if ((node.getUserObject() instanceof FileGroup)
                        || (node.getUserObject() instanceof FileSystemObject) || ((getEntities().size() > 1)
                                && (node.getUserObject() instanceof FileGroupCollection))) {
                    canDelete = true;//ww  w .  j a  v a 2 s  .c om
                    break;
                }
            }
        }
    }
    return canDelete;
}

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

public void resequenceEntity() {
    JTree tree = theEntityTree;
    TreePath[] paths = tree.getSelectionPaths();
    for (int i = 0; i < paths.length; i++) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
        if ((node.getUserObject() instanceof FileGroup) || (node.getUserObject() instanceof FileSystemObject)
                || ((getEntities().size() > 1) && (node.getUserObject() instanceof FileGroupCollection))) {
            FileGroup group = (FileGroup) node.getUserObject();
            String sequenceNumber = manualDepositFrame.getInput("Enter Sequence Number",
                    "Enter new sequence number", String.format("%d", group.getRevisionNumber()));
            if (sequenceNumber != null) {
                try {
                    int newSequence = Integer.parseInt(sequenceNumber);
                    group.setRevisionNumber(newSequence);
                } catch (Exception ex) {
                    manualDepositFrame.showError("Invalid Sequence Number",
                            "Sequence number must be a valid number", ex);
                }/*  ww w  .  j ava2s.  c  om*/
            }
        }
    }
}