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:de.tor.tribes.ui.views.DSWorkbenchSelectionFrame.java

public List<Village> getSelectedElements() {
    TreePath[] paths = jSelectionTree.getSelectionModel().getSelectionPaths();
    List<Village> result = new LinkedList<>();
    if (paths == null) {
        return result;
    }//from  w  w w.j  a  v a  2s  .co m
    for (TreePath p : paths) {
        Object o = p.getLastPathComponent();
        if (o instanceof AllyNode) {
            Ally a = ((AllyNode) o).getUserObject();
            Village[] copy = treeData.toArray(new Village[] {});
            for (Village v : copy) {
                if (v.getTribe() == Barbarians.getSingleton() && a.equals(BarbarianAlly.getSingleton())) {
                    //remove barbarian ally member
                    if (!result.contains(v)) {
                        result.add(v);
                    }
                } else if (v.getTribe() != Barbarians.getSingleton() && v.getTribe().getAlly() == null
                        && a.equals(NoAlly.getSingleton())) {
                    //remove no-ally member
                    if (!result.contains(v)) {
                        result.add(v);
                    }
                } else if (v.getTribe() != Barbarians.getSingleton() && v.getTribe().getAlly() != null
                        && a.equals(v.getTribe().getAlly())) {
                    //remove if ally is equal
                    if (!result.contains(v)) {
                        result.add(v);
                    }
                }
            }
        } else if (o instanceof TribeNode) {
            Tribe t = ((TribeNode) o).getUserObject();
            Village[] copy = treeData.toArray(new Village[] {});
            for (Village v : copy) {
                if (v.getTribe() == Barbarians.getSingleton() && t.equals(Barbarians.getSingleton())) {
                    //if village is barbarian village and selected tribe are barbs, remove village
                    if (!result.contains(v)) {
                        result.add(v);
                    }
                } else if (v.getTribe() != null && !v.getTribe().equals(Barbarians.getSingleton()) && t != null
                        && v.getTribe().getId() == t.getId()) {
                    //selected tribe are no barbs, so check tribes to be equal
                    if (!result.contains(v)) {
                        result.add(v);
                    }
                }
            }
        } else if (o instanceof TagNode) {
            Tag t = ((TagNode) o).getUserObject();
            Village[] copy = treeData.toArray(new Village[] {});
            for (Village v : copy) {
                if (v != null && t != null && t.tagsVillage(v.getId())) {
                    if (!result.contains(v)) {
                        result.add(v);
                    }
                }
            }
        } else if (o instanceof VillageNode) {
            Village v = ((VillageNode) o).getUserObject();
            if (!result.contains(v)) {
                result.add(v);
            }
        } else if (o != null && o.equals(mRoot)) {
            //remove all
            result = new LinkedList<>(treeData);
            //nothing more than everything can be removed
            return result;
        } else {
            //remove nothing
        }
    }
    return result;
}

From source file:EditorPaneExample18.java

public EditorPaneExample18() {
    super("JEditorPane Example 18");

    pane = new JEditorPane();
    pane.setEditable(true); // Editable
    getContentPane().add(new JScrollPane(pane), "Center");

    // Add a menu bar
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);/*from   w ww  .  ja v  a 2s.  co  m*/

    // Populate it
    createMenuBar();

    // Build the panel of controls
    JPanel panel = new JPanel();

    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = 1;
    c.gridheight = 1;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    c.weighty = 0.0;

    JLabel urlLabel = new JLabel("URL: ", JLabel.RIGHT);
    panel.add(urlLabel, c);
    JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT);
    c.gridy = 1;
    panel.add(loadingLabel, c);
    JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT);
    c.gridy = 2;
    panel.add(typeLabel, c);
    c.gridy = 3;
    panel.add(new JLabel(LOAD_TIME), c);

    c.gridy = 4;
    c.gridwidth = 2;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.WEST;
    onlineLoad = new JCheckBox("Online Load");
    panel.add(onlineLoad, c);
    onlineLoad.setSelected(true);
    onlineLoad.setForeground(typeLabel.getForeground());

    c.gridy = 5;
    c.gridwidth = 2;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.WEST;
    editableBox = new JCheckBox("Editable JEditorPane");
    panel.add(editableBox, c);
    editableBox.setSelected(true);
    editableBox.setForeground(typeLabel.getForeground());

    c.gridy = 6;
    c.weightx = 0.0;
    JButton saveButton = new JButton("Save");
    panel.add(saveButton, c);
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            EditorKit kit = pane.getEditorKit();
            try {
                if (kit instanceof RTFEditorKit) {
                    kit.write(System.out, pane.getDocument(), 0, pane.getDocument().getLength());
                    System.out.flush();
                } else {
                    if (writer == null) {
                        writer = new OutputStreamWriter(System.out);
                        pane.write(writer);
                        writer.flush();
                    }
                    kit.write(writer, pane.getDocument(), 0, pane.getDocument().getLength());
                    writer.flush();
                }
            } catch (Exception e) {
                System.out.println("Write failed");
            }
        }
    });

    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.HORIZONTAL;

    urlCombo = new JComboBox();
    panel.add(urlCombo, c);
    urlCombo.setEditable(true);
    loadingState = new JLabel(spaces, JLabel.LEFT);
    loadingState.setForeground(Color.black);
    c.gridy = 1;
    panel.add(loadingState, c);
    loadedType = new JLabel(spaces, JLabel.LEFT);
    loadedType.setForeground(Color.black);
    c.gridy = 2;
    panel.add(loadedType, c);
    timeLabel = new JLabel("");
    c.gridy = 3;
    panel.add(timeLabel, c);

    getContentPane().add(panel, "South");

    // Register a custom EditorKit for HTML
    ClassLoader loader = getClass().getClassLoader();
    if (loader != null) {
        // Java 2
        JEditorPane.registerEditorKitForContentType("text/html",
                "AdvancedSwing.Chapter4.HiddenViewHTMLEditorKit", loader);
    } else {
        // JDK 1.1
        JEditorPane.registerEditorKitForContentType("text/html",
                "AdvancedSwing.Chapter4.HiddenViewHTMLEditorKit");
    }

    // Allocate the empty tree model
    DefaultMutableTreeNode emptyRootNode = new DefaultMutableTreeNode("Empty");
    emptyModel = new DefaultTreeModel(emptyRootNode);

    // Create and place the heading tree
    tree = new JTree(emptyModel);
    tree.setPreferredSize(new Dimension(200, 200));
    getContentPane().add(new JScrollPane(tree), "East");

    // Change page based on combo selection
    urlCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (populatingCombo == true) {
                return;
            }
            Object selection = urlCombo.getSelectedItem();
            loadNewPage(selection);
        }
    });

    // Change editability based on the checkbox
    editableBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            pane.setEditable(editableBox.isSelected());
            pane.revalidate();
            pane.repaint();
        }
    });

    // Listen for page load to complete
    pane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("page")) {
                loadComplete();
                displayLoadTime();
                populateCombo(findLinks(pane.getDocument(), null));
                TreeNode node = buildHeadingTree(pane.getDocument());
                tree.setModel(new DefaultTreeModel(node));

                createMenuBar();
                enableMenuBar(true);
                getRootPane().revalidate();

                enableInput();
                loadingPage = false;
            }
        }
    });

    // Listener for tree selection
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent evt) {
            TreePath path = evt.getNewLeadSelectionPath();
            if (path != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                Object userObject = node.getUserObject();
                if (userObject instanceof Heading) {
                    Heading heading = (Heading) userObject;
                    try {
                        Rectangle textRect = pane.modelToView(heading.getOffset());
                        textRect.y += 3 * textRect.height;
                        pane.scrollRectToVisible(textRect);
                    } catch (BadLocationException e) {
                    }
                }
            }
        }
    });

    // Listener for hypertext events
    pane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent evt) {
            // Ignore hyperlink events if the frame is busy
            if (loadingPage == true) {
                return;
            }
            if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                JEditorPane sp = (JEditorPane) evt.getSource();
                if (evt instanceof HTMLFrameHyperlinkEvent) {
                    HTMLDocument doc = (HTMLDocument) sp.getDocument();
                    doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) evt);
                } else {
                    loadNewPage(evt.getURL());
                }
            } else if (evt.getEventType() == HyperlinkEvent.EventType.ENTERED) {
                pane.setCursor(handCursor);
            } else if (evt.getEventType() == HyperlinkEvent.EventType.EXITED) {
                pane.setCursor(defaultCursor);
            }
        }
    });
}

From source file:DragDropTreeExample.java

protected File findTargetDirectory(Point location) {
    TreePath treePath = tree.getPathForLocation(location.x, location.y);
    if (treePath != null) {
        FileTree.FileTreeNode node = (FileTree.FileTreeNode) treePath.getLastPathComponent();
        // Only allow a drop on a writable directory
        if (node.isDir()) {
            try {
                File f = new File(node.getFullName());
                if (f.canWrite()) {
                    return f;
                }//from w  ww.jav a 2s. com
            } catch (Exception e) {
            }
        }
    }
    return null;
}

From source file:de.codesourcery.jasm16.ide.ui.views.SourceEditorView.java

private void setupASTInspector() {
    astInspector = new JFrame("AST");

    final MouseAdapter treeMouseListener = new MouseAdapter() {
        @Override//from   w  w  w  .  j  av a  2 s  . c o  m
        public void mouseMoved(MouseEvent e) {
            String text = null;
            TreePath path = astTree.getClosestPathForLocation(e.getX(), e.getY());

            if (path != null) {
                ASTNode node = (ASTNode) path.getLastPathComponent();
                if (node instanceof InstructionNode) { // TODO: debug code, remove when done
                    text = null;
                }
                try {
                    text = getCurrentCompilationUnit().getSource(node.getTextRegion());
                } catch (Exception ex) {
                    text = "Node " + node.getClass().getSimpleName() + " has invalid text region "
                            + node.getTextRegion();
                }
                text = "<HTML>" + text.replace("\n", "<BR>") + "</HTML>";
            }
            if (!ObjectUtils.equals(astTree.getToolTipText(), text)) {
                astTree.setToolTipText(text);
            }
        }
    };
    astTree.addMouseMotionListener(treeMouseListener);
    astTree.setCellRenderer(new ASTTreeCellRenderer());

    final JScrollPane pane = new JScrollPane(astTree);
    setColors(pane);
    pane.setPreferredSize(new Dimension(400, 600));

    GridBagConstraints cnstrs = constraints(0, 0, true, false, GridBagConstraints.REMAINDER);
    cnstrs.weighty = 0.9;
    panel.add(pane, cnstrs);

    // add symbol table 
    symbolTable.setFillsViewportHeight(true);
    MouseAdapter mouseListener = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {
                int viewRow = symbolTable.rowAtPoint(e.getPoint());
                if (viewRow != -1) {
                    final int modelRow = symbolTable.convertRowIndexToModel(viewRow);
                    final ISymbol symbol = symbolTableModel.getSymbolForRow(modelRow);
                    final int caretPosition = symbol.getLocation().getStartingOffset();

                    IEditorView editor = null;
                    if (DefaultResourceMatcher.INSTANCE.isSame(symbol.getCompilationUnit().getResource(),
                            getSourceFromMemory())) {
                        editor = SourceEditorView.this;
                    } else if (getViewContainer() instanceof EditorContainer) {
                        final EditorContainer parent = (EditorContainer) getViewContainer();
                        try {
                            editor = parent.openResource(workspace, getCurrentProject(),
                                    symbol.getCompilationUnit().getResource(), caretPosition);
                        } catch (IOException e1) {
                            LOG.error("mouseClicked(): Failed top open "
                                    + symbol.getCompilationUnit().getResource(), e1);
                            return;
                        }
                    }
                    if (editor instanceof SourceCodeView) {
                        ((SourceCodeView) editor).moveCursorTo(caretPosition, true);
                    }
                }
            }
        }
    };
    symbolTable.addMouseListener(mouseListener);

    final JScrollPane tablePane = new JScrollPane(symbolTable);
    setColors(tablePane);
    tablePane.setPreferredSize(new Dimension(400, 200));

    cnstrs = constraints(0, 1, true, true, GridBagConstraints.REMAINDER);
    cnstrs.weighty = 0.1;
    panel.add(pane, cnstrs);

    final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane, tablePane);
    setColors(split);

    // setup content pane
    astInspector.getContentPane().add(split);
    setColors(astInspector.getContentPane());
    astInspector.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    astInspector.pack();
}

From source file:com.nbt.TreeFrame.java

private void add(final Tag<?> tag, TreePath path) {
    Object last = path.getLastPathComponent();
    if (!(last instanceof Mutable)) {
        TreePath parentPath = path.getParentPath();
        add(tag, parentPath);//from   ww  w .  j a va  2  s .  c om
        return;
    }
    Object scroll = tag;
    if (last instanceof Mutable) {
        Mutable mutable = (Mutable) last;
        if (last instanceof ByteArrayTag) {
            mutable.add(null);
        } else if (last instanceof ByteWrapper) {
            ByteWrapper wrapper = (ByteWrapper) last;
            int index = wrapper.getIndex() + 1;
            mutable.add(index, null);
            scroll = index;
        } else if (last instanceof ListTag) {
            mutable.add(tag);
        } else if (last instanceof CompoundTag || last instanceof TagWrapper) {
            mutable.add(tag);
        }
        nodesInserted(last, path);
    }
    scrollTo(scroll);
}

From source file:net.sf.jabref.gui.FindUnlinkedFilesDialog.java

/**
 * Expands or collapses the specified tree according to the
 * <code>expand</code>-parameter.
 *//*from w  w w. j  a v  a2  s . c  o  m*/
private void expandTree(JTree currentTree, TreePath parent, boolean expand) {
    TreeNode node = (TreeNode) parent.getLastPathComponent();
    if (node.getChildCount() >= 0) {
        for (Enumeration<TreeNode> e = node.children(); e.hasMoreElements();) {
            TreePath path = parent.pathByAddingChild(e.nextElement());
            expandTree(currentTree, path, expand);
        }
    }
    if (expand) {
        currentTree.expandPath(parent);
    } else {
        currentTree.collapsePath(parent);
    }
}

From source file:com.nbt.TreeFrame.java

protected void updateActions() {
    Map<Integer, Action> actionMap = new LinkedHashMap<Integer, Action>();
    actionMap.put(NBTConstants.TYPE_BYTE, addByteAction);
    actionMap.put(NBTConstants.TYPE_SHORT, addShortAction);
    actionMap.put(NBTConstants.TYPE_INT, addIntAction);
    actionMap.put(NBTConstants.TYPE_LONG, addLongAction);
    actionMap.put(NBTConstants.TYPE_FLOAT, addFloatAction);
    actionMap.put(NBTConstants.TYPE_DOUBLE, addDoubleAction);
    actionMap.put(NBTConstants.TYPE_BYTE_ARRAY, addByteArrayAction);
    actionMap.put(NBTConstants.TYPE_STRING, addStringAction);
    actionMap.put(NBTConstants.TYPE_LIST, addListAction);
    actionMap.put(NBTConstants.TYPE_COMPOUND, addCompoundAction);
    for (Action action : actionMap.values())
        action.setEnabled(false);// w w w .j  a v a2  s.  co  m

    Action[] actions = { openAction };
    for (Action action : actions)
        action.setEnabled(false);

    if (treeTable == null)
        return;

    int row = treeTable.getSelectedRow();
    deleteAction.setEnabled(row > 0);
    if (row == -1)
        return;
    TreePath path = treeTable.getPathForRow(row);
    Object last = path.getLastPathComponent();
    TreePath parentPath = path.getParentPath();
    Object parentLast = parentPath == null ? null : parentPath.getLastPathComponent();

    if (last instanceof ByteArrayTag || parentLast instanceof ByteArrayTag || last instanceof ByteWrapper
            || parentLast instanceof ByteWrapper) {
        addByteAction.setEnabled(true);
    } else if (last instanceof ListTag || parentLast instanceof ListTag) {
        if (!(last instanceof ListTag))
            last = parentLast;

        ListTag list = (ListTag) last;
        @SuppressWarnings("unchecked")
        Class<Tag<?>> c = (Class<Tag<?>>) list.getType();
        int type = NBTUtils.getTypeCode(c);
        Action action = actionMap.get(type);
        action.setEnabled(true);
    } else if (last instanceof CompoundTag || parentLast instanceof CompoundTag || last instanceof TagWrapper
            || parentLast instanceof TagWrapper) {
        for (Action action : actionMap.values())
            action.setEnabled(true);
    } else if (last instanceof Region || last instanceof World || last instanceof NBTFileBranch) {
        openAction.setEnabled(true);
    }
}

From source file:EditorPaneExample20.java

public EditorPaneExample20() {
    super("JEditorPane Example 20");

    pane = new JEditorPane();
    pane.setEditable(true); // Editable
    getContentPane().add(new JScrollPane(pane), "Center");

    // Add a menu bar
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);//from   www .j av a2s.co  m

    // Populate it
    createMenuBar();

    // Build the panel of controls
    JPanel panel = new JPanel();

    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = 1;
    c.gridheight = 1;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    c.weighty = 0.0;

    JLabel urlLabel = new JLabel("URL: ", JLabel.RIGHT);
    panel.add(urlLabel, c);
    JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT);
    c.gridy = 1;
    panel.add(loadingLabel, c);
    JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT);
    c.gridy = 2;
    panel.add(typeLabel, c);
    c.gridy = 3;
    panel.add(new JLabel(LOAD_TIME), c);

    c.gridy = 4;
    c.gridwidth = 2;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.WEST;
    onlineLoad = new JCheckBox("Online Load");
    panel.add(onlineLoad, c);
    onlineLoad.setSelected(true);
    onlineLoad.setForeground(typeLabel.getForeground());

    c.gridy = 5;
    c.gridwidth = 2;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.WEST;
    editableBox = new JCheckBox("Editable JEditorPane");
    panel.add(editableBox, c);
    editableBox.setSelected(true);
    editableBox.setForeground(typeLabel.getForeground());

    c.gridy = 6;
    c.weightx = 0.0;
    JButton saveButton = new JButton("Save");
    panel.add(saveButton, c);
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            EditorKit kit = pane.getEditorKit();
            try {
                if (kit instanceof RTFEditorKit) {
                    kit.write(System.out, pane.getDocument(), 0, pane.getDocument().getLength());
                    System.out.flush();
                } else {
                    if (writer == null) {
                        writer = new OutputStreamWriter(System.out);
                        pane.write(writer);
                        writer.flush();
                    }
                    kit.write(writer, pane.getDocument(), 0, pane.getDocument().getLength());
                    writer.flush();
                }
            } catch (Exception e) {
                System.out.println("Write failed");
            }
        }
    });

    c.gridx = 1;
    insertButton = new JButton("Insert HTML");
    panel.add(insertButton, c);
    insertButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (insertFrame == null) {
                insertFrame = new HTMLInsertFrame("HTML Insertion", pane);
                Point pt = EditorPaneExample20.this.getLocationOnScreen();
                Dimension d = EditorPaneExample20.this.getSize();
                insertFrame.setLocation(pt.x + d.width, pt.y);
                insertFrame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent evt) {
                        insertFrame.dispose();
                        insertFrame = null;
                        setInsertButtonState();
                    }
                });
                insertButton.setEnabled(false);
                insertFrame.setVisible(true);
            }
        }
    });
    insertButton.setEnabled(false);

    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.HORIZONTAL;

    urlCombo = new JComboBox();
    panel.add(urlCombo, c);
    urlCombo.setEditable(true);
    loadingState = new JLabel(spaces, JLabel.LEFT);
    loadingState.setForeground(Color.black);
    c.gridy = 1;
    panel.add(loadingState, c);
    loadedType = new JLabel(spaces, JLabel.LEFT);
    loadedType.setForeground(Color.black);
    c.gridy = 2;
    panel.add(loadedType, c);
    timeLabel = new JLabel("");
    c.gridy = 3;
    panel.add(timeLabel, c);

    getContentPane().add(panel, "South");

    // Register a custom EditorKit for HTML
    ClassLoader loader = getClass().getClassLoader();
    if (loader != null) {
        // Java 2
        JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit",
                loader);
    } else {
        // JDK 1.1
        JEditorPane.registerEditorKitForContentType("text/html",
                "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit");
    }

    // Allocate the empty tree model
    DefaultMutableTreeNode emptyRootNode = new DefaultMutableTreeNode("Empty");
    emptyModel = new DefaultTreeModel(emptyRootNode);

    // Create and place the heading tree
    tree = new JTree(emptyModel);
    tree.setPreferredSize(new Dimension(200, 200));
    getContentPane().add(new JScrollPane(tree), "East");

    // Change page based on combo selection
    urlCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (populatingCombo == true) {
                return;
            }
            Object selection = urlCombo.getSelectedItem();
            loadNewPage(selection);
        }
    });

    // Change editability based on the checkbox
    editableBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            pane.setEditable(editableBox.isSelected());
            pane.revalidate();
            pane.repaint();
        }
    });

    // Listen for page load to complete
    pane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("page")) {
                loadComplete();
                displayLoadTime();
                populateCombo(findLinks(pane.getDocument(), null));
                TreeNode node = buildHeadingTree(pane.getDocument());
                tree.setModel(new DefaultTreeModel(node));

                createMenuBar();
                enableMenuBar(true);
                getRootPane().revalidate();

                enableInput();
                loadingPage = false;
            }
        }
    });

    // Listener for tree selection
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent evt) {
            TreePath path = evt.getNewLeadSelectionPath();
            if (path != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                Object userObject = node.getUserObject();
                if (userObject instanceof Heading) {
                    Heading heading = (Heading) userObject;
                    try {
                        Rectangle textRect = pane.modelToView(heading.getOffset());
                        textRect.y += 3 * textRect.height;
                        pane.scrollRectToVisible(textRect);
                    } catch (BadLocationException e) {
                    }
                }
            }
        }
    });

    // Listener for hypertext events
    pane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent evt) {
            // Ignore hyperlink events if the frame is busy
            if (loadingPage == true) {
                return;
            }
            if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                JEditorPane sp = (JEditorPane) evt.getSource();
                if (evt instanceof HTMLFrameHyperlinkEvent) {
                    HTMLDocument doc = (HTMLDocument) sp.getDocument();
                    doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) evt);
                } else {
                    loadNewPage(evt.getURL());
                }
            } else if (evt.getEventType() == HyperlinkEvent.EventType.ENTERED) {
                pane.setCursor(handCursor);
            } else if (evt.getEventType() == HyperlinkEvent.EventType.EXITED) {
                pane.setCursor(defaultCursor);
            }
        }
    });
}

From source file:DragDropTreeExample.java

protected boolean dropFile(int action, Transferable transferable, Point location)
        throws IOException, UnsupportedFlavorException, MalformedURLException {
    List files = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
    TreePath treePath = tree.getPathForLocation(location.x, location.y);
    File targetDirectory = findTargetDirectory(location);
    if (treePath == null || targetDirectory == null) {
        return false;
    }//from w  ww  .  j a  v  a 2 s.  com
    FileTree.FileTreeNode node = (FileTree.FileTreeNode) treePath.getLastPathComponent();

    // Highlight the drop location while we perform the drop
    tree.setSelectionPath(treePath);

    // Get File objects for all files being
    // transferred, eliminating duplicates.
    File[] fileList = getFileList(files);

    // Don't overwrite files by default
    copyOverExistingFiles = false;

    // Copy or move each source object to the target
    for (int i = 0; i < fileList.length; i++) {
        File f = fileList[i];
        if (f.isDirectory()) {
            transferDirectory(action, f, targetDirectory, node);
        } else {
            try {
                transferFile(action, fileList[i], targetDirectory, node);
            } catch (IllegalStateException e) {
                // Cancelled by user
                return false;
            }
        }
    }

    return true;
}

From source file:net.sf.jabref.gui.groups.GroupSelector.java

private List<GroupTreeNodeViewModel> getLeafsOfSelection() {
    TreePath[] selection = groupsTree.getSelectionPaths();
    if ((selection == null) || (selection.length == 0)) {
        return new ArrayList<>();
    }/*from ww  w . j  av a2 s .  c o m*/

    List<GroupTreeNodeViewModel> selectedLeafs = new ArrayList<>(selection.length);
    for (TreePath path : selection) {
        selectedLeafs.add((GroupTreeNodeViewModel) path.getLastPathComponent());
    }
    return selectedLeafs;
}