Example usage for javax.swing JTree getRowForLocation

List of usage examples for javax.swing JTree getRowForLocation

Introduction

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

Prototype

public int getRowForLocation(int x, int y) 

Source Link

Document

Returns the row for the specified location.

Usage

From source file:eu.europa.ec.markt.dss.applet.view.validationpolicy.EditView.java

private void registerMouseListener(final JTree tree) {

    MouseListener mouseAdapter = new MouseAdapter() {
        public void mousePressed(MouseEvent mouseEvent) {
            if (mouseEvent.getButton() == MouseEvent.BUTTON3) {
                final int selectedRow = tree.getRowForLocation(mouseEvent.getX(), mouseEvent.getY());
                final TreePath selectedPath = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                if (selectedRow != -1) {
                    final XmlDomAdapterNode clickedItem = (XmlDomAdapterNode) selectedPath
                            .getLastPathComponent();
                    final boolean isLeaf = tree.getModel().isLeaf(selectedPath.getLastPathComponent());
                    // Do nothing on root element
                    if (selectedPath.getPathCount() > 1) {
                        // find the allowed actions, to know if a popup menu should be displayed and the content of the popup menu + action handlers
                        if (clickedItem.node instanceof Element) {
                            nodeActionAdd(mouseEvent, selectedRow, selectedPath, clickedItem, tree);
                        } else if (isLeaf) {
                            valueLeafActionEdit(mouseEvent, selectedPath, clickedItem, tree);
                        }/*  www  .  jav  a 2 s . c om*/
                    }
                }
            }
        }
    };
    tree.addMouseListener(mouseAdapter);
}

From source file:eu.europa.esig.dss.applet.view.validationpolicy.EditView.java

private void registerMouseListener(final JTree tree) {

    MouseListener mouseAdapter = new MouseAdapter() {
        @Override//from  w w w  .  j  a v a  2 s. com
        public void mousePressed(MouseEvent mouseEvent) {
            if (mouseEvent.getButton() == MouseEvent.BUTTON3) {
                final int selectedRow = tree.getRowForLocation(mouseEvent.getX(), mouseEvent.getY());
                final TreePath selectedPath = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                if (selectedRow != -1) {
                    final XmlDomAdapterNode clickedItem = (XmlDomAdapterNode) selectedPath
                            .getLastPathComponent();
                    final boolean isLeaf = tree.getModel().isLeaf(selectedPath.getLastPathComponent());
                    // Do nothing on root element
                    if (selectedPath.getPathCount() > 1) {
                        // find the allowed actions, to know if a popup menu should be displayed and the content of the popup menu + action handlers
                        if (clickedItem.node instanceof Element) {
                            nodeActionAdd(mouseEvent, selectedRow, selectedPath, clickedItem, tree);
                        } else if (isLeaf) {
                            valueLeafActionEdit(mouseEvent, selectedPath, clickedItem, tree);
                        }
                    }
                }
            }
        }
    };
    tree.addMouseListener(mouseAdapter);
}

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

public Main(TaskTree taskTree) {
    super();/*w  w w. j a va  2  s  .co m*/

    this.taskTree = taskTree;

    this.setTitle("Task Tree");
    this.setSize(new Dimension(300, 500));
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel quickInPanel = new JPanel(new BorderLayout());
    this.quickIn = new JTextArea();
    this.quickIn.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent arg0) {
            if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
                String newText = quickIn.getText().trim();
                if (newText != null && newText.length() > 0) {
                    addTask(Main.this.taskTree.getRoot(), 0, newText, true);
                    try {
                        Main.this.taskTree.changesMade();
                    } catch (Exception e) {
                        error(e.getMessage());
                    }
                }
                quickIn.setText("");
            }
        }
    });
    this.quickIn.setPreferredSize(new Dimension(300, 75));
    this.quickIn.setBorder(BorderFactory.createTitledBorder("Quick Input"));
    quickInPanel.add(this.quickIn, BorderLayout.CENTER);
    this.syncButton = new JButton("Sync");
    this.syncButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new SyncThread(Main.this).start();
        }
    });
    quickInPanel.add(this.syncButton, BorderLayout.EAST);
    this.getContentPane().add(quickInPanel, BorderLayout.NORTH);

    this.tree = new JTree(taskTree.getTreeModel());
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() {
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
            Object newVal = htmlFilter(String.valueOf(node.getUserObject()));
            if (node.getChildCount() > 0 && !tree.isExpanded(new TreePath(node.getPath()))) {
                DefaultMutableTreeNode firstLeaf = (DefaultMutableTreeNode) node.getFirstLeaf();
                newVal = htmlFilter(String.valueOf(node.getUserObject()))
                        + " <span style='color:silver;font-style:italic'>" + "("
                        + String.valueOf(firstLeaf.getUserObject()) + ")</span>";
            }
            newVal = "<html>" + newVal + "</html>";

            return super.getTreeCellRendererComponent(tree, newVal, selected, expanded, leaf, row, hasFocus);
        }
    };
    ImageIcon bulletIcon = new ImageIcon(Main.class.getResource("bullet.gif"));
    renderer.setLeafIcon(bulletIcon);
    renderer.setOpenIcon(bulletIcon);
    renderer.setClosedIcon(bulletIcon);
    renderer.setBorder(BorderFactory.createEmptyBorder(4, 0, 4, 0));
    this.tree.setCellRenderer(renderer);
    this.tree.setRootVisible(false);
    this.tree.setShowsRootHandles(true);
    this.tree.addMouseListener(new MouseAdapter() {
        protected void doSelectRow(MouseEvent arg0) {
            int row = tree.getRowForLocation(arg0.getX(), arg0.getY());
            if (row != -1) {
                tree.setSelectionRow(row);
                if (arg0.isPopupTrigger()) {
                    popup.show(tree, arg0.getX(), arg0.getY());
                }
            }
        }

        public void mousePressed(MouseEvent arg0) {
            doSelectRow(arg0);
        }

        public void mouseReleased(MouseEvent arg0) {
            doSelectRow(arg0);
        }
    });
    JScrollPane treeScroll = new JScrollPane(tree);
    treeScroll.setBorder(BorderFactory.createTitledBorder("Task List"));
    this.getContentPane().add(treeScroll, BorderLayout.CENTER);

    this.popup = new JPopupMenu();
    JMenuItem addBefore = new JMenuItem("Add Before");
    addBefore.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = parent.getIndex(selected);
            promptAndInsert(parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(addBefore);
    JMenuItem addAfter = new JMenuItem("Add After");
    addAfter.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = parent.getIndex(selected) + 1;
            promptAndInsert(parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(addAfter);
    JMenuItem addNested = new JMenuItem("Add Nested");
    addNested.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            int pos = selected.getChildCount();
            promptAndInsert(selected, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                ex.getMessage();
            }
        }
    });
    this.popup.add(addNested);
    this.popup.add(new JSeparator());
    JMenuItem moveTop = new JMenuItem("Move to Top");
    moveTop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            moveTask(selected, parent, 0);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveTop);
    JMenuItem moveUp = new JMenuItem("Move Up");
    moveUp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = Math.max(parent.getIndex(selected) - 1, 0);
            moveTask(selected, parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveUp);
    JMenuItem moveDown = new JMenuItem("Move Down");
    moveDown.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = Math.min(parent.getIndex(selected) + 1, parent.getChildCount() - 1);
            moveTask(selected, parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveDown);
    JMenuItem moveBottom = new JMenuItem("Move to Bottom");
    moveBottom.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            moveTask(selected, parent, parent.getChildCount() - 1);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveBottom);
    this.popup.add(new JSeparator());
    JMenuItem rename = new JMenuItem("Edit");
    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            String newText = prompt((String) selected.getUserObject());
            if (newText != null && newText.length() > 0) {
                selected.setUserObject(newText);
                Main.this.taskTree.getTreeModel().reload(selected);
                try {
                    Main.this.taskTree.changesMade();
                } catch (Exception ex) {
                    error(ex.getMessage());
                }
            }
        }
    });
    this.popup.add(rename);
    JMenuItem delete = new JMenuItem("Delete");
    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            promptAndRemove(getSelectedNode());
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(delete);

    this.setVisible(true);

    loadConfig();
    load();

    syncButton.setVisible(this.taskTree.hasSyncCapability());
}

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   w  ww . j  a  v a  2  s .  c  o m*/
    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);//from w ww  . j  av  a2  s .c  o  m
    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   w  ww  . ja  v  a  2 s .  c  om*/
    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:org.nuclos.client.ui.collect.searcheditor.SearchEditorController.java

/**
 * adds a mouselistener to the given <code>tree</code>,
 * in order to enable popup menus and double click.
 * @param tree/*from  w w  w .  ja  v a2  s.co m*/
 */
private void addMouseListenerTo(final JTree tree) {
    tree.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent ev) {
            mouseEventOnNode(ev);
        }

        @Override
        public void mouseReleased(MouseEvent ev) {
            mouseEventOnNode(ev);
        }

        @Override
        public void mouseClicked(MouseEvent ev) {
            mouseEventOnNode(ev);
        }

        private void mouseEventOnNode(MouseEvent ev) {
            final int selRow = tree.getRowForLocation(ev.getX(), ev.getY());
            final TreePath treepath = tree.getPathForLocation(ev.getX(), ev.getY());
            if (selRow != -1) {
                SearchEditorController.this.mouseEventOnNode(treepath, ev);
            }
        }
    });
}