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


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

输出

更新时间: 12-2-2020

709 次查看

开启你的 职业生涯

完成课程以获得认证

立即开始
广告