如何在 Java 中实现鼠标右键单击 JTree 的每个节点?\

awtjavaobject oriented programmingprogrammingswing

JTree JComponent  类的子类,可用于通过在节点上添加 节点  来显示具有 层次结构属性 的数据,并保留父节点和子节点的概念。树中的每个元素都成为一个 节点。节点是 可展开和可折叠 的。我们可以使用 MouseAdapter  类的 mouseReleased() 方法实现鼠标右键单击 JTree 的每个节点,并需要调用 JPopupMenu  类的 show() 方法来显示树节点上的弹出菜单。

示例

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);
   }
}

输出


相关文章