Alex
Alex

Reputation: 33

Issue with JPopupMenu in a JTree

I have this issue. In a custom JTree I implemented a JPopupMenu to display different JMenuItem according to the node selected using a MouseListener. The JPopupMenu is shown when the mouse right button is clicked. The problem is that if I don’t choose an Item from the PopupMenu but instead I select another node in the tree, either with right or left buttons, this event is never caught by the tree MouseListener Could anyone point me in the right direction to solve this? In case an example is available I’ll appreciate it. Thanks.

Upvotes: 2

Views: 1770

Answers (1)

jridley
jridley

Reputation: 236

I would suggest maybe using a TreeSelectionListener for determining changes in selected node as opposed to the MouseListener and repopulating the JPopupMenu at that point, but that's your choice.

Trying to emulate your example, I was wondering, which methods did you override in your mouse listener? In this simple example, the listener seems to get the events regardless of if the popup menu is showing or not.

EDIT - see my comment below, but the right click not selecting a node is default behavior. This example will select the closest node to where the right click was made if possible.

public class SampleTree extends JFrame {
    private JPopupMenu menu = new JPopupMenu("Popup");

    public SampleTree() throws HeadlessException {
        super("Tree");
        final JTree tree = new JTree();

        tree.addMouseListener(new MouseAdapter() {
           public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    TreePath tp = tree.getClosestPathForLocation(e.getX(),e.getY());
                    if (tp != null) {
                        System.out.println(tp);
                        tree.setSelectionPath(tp);
                    }
                    menu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });

        String letters = "ABCDEF";

        for (final char letter : letters.toCharArray()) {
            JMenuItem item = new JMenuItem(String.valueOf(letter));
            item.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(SampleTree.this, "You chose the letter: " + letter);
                }
            });
            menu.add(item);
        }

        add(new JScrollPane(tree));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SampleTree st = new SampleTree();
                st.setSize(200, 200);
                st.setLocationRelativeTo(null);
                st.setVisible(true);
            }
        });
    }
}

Upvotes: 2

Related Questions