How to implement the mouse right-click on each node of JTree in Java?


A JTree is a subclass of JComponent class that can be used to display the data with the hierarchical properties by adding nodes to nodes and keeps the concept of parent and child node. Each element in the tree becomes a node. The nodes are expandable and collapsible. We can implement the mouse right-click on each node of a JTree using the mouseReleased() method of MouseAdapter class and need to call show() method of JPopupMenu class to show the popup menu on the tree node.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class JTreeRightClickTest extends JFrame {
   public JTreeRightClickTest() {
      DefaultMutableTreeNode root = createNodes();
      JTree tree = new JTree(root);
      final TreePopup treePopup = new TreePopup(tree);
      tree.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent e) {
            if(e.isPopupTrigger()) {
               treePopup.show(e.getComponent(), e.getX(), e.getY());
            }
         }
      });
      add(new JScrollPane(tree), BorderLayout.NORTH);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(400, 300);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Technology");
      DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Java");
      DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Python");
      DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Selenium");
      node1.add(new DefaultMutableTreeNode("Programming Language"));
      node2.add(new DefaultMutableTreeNode("Programming Language"));
      node3.add(new DefaultMutableTreeNode("Testing Framework"));
      root.add(node1);
      root.add(node2);
      root.add(node3);
      return root;
   }
   public static void main(String args[]) {
      new JTreeRightClickTest();
   }
}
class TreePopup extends JPopupMenu {
   public TreePopup(JTree tree) {
      JMenuItem delete = new JMenuItem("Delete");
      JMenuItem add = new JMenuItem("Add");
      delete.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Delete child");
         }
      });
      add.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Add child");
         }
      });
      add(delete);
      add(new JSeparator());
      add(add);
   }
}

Output

Updated on: 12-Feb-2020

506 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements