JAVA GUI界面编程实现树节点的事件监听

一、创建滚动条容器,将该容器添加到当前框架。(因为树模型需要在滚动条中才能显示完全)

JScrollPane scrollPane = new JScrollPane(); 

二、创建树模型

JTree tree = new JTree(); 

DefaultMutableTreeNode dft =new DefaultMutableTreeNode("Jtree") {
   {
    DefaultMutableTreeNode node_1;
    node_1 = new DefaultMutableTreeNode("colors");
     node_1.add(new DefaultMutableTreeNode("blue"));
     node_1.add(new DefaultMutableTreeNode("violet"));
     node_1.add(new DefaultMutableTreeNode("red"));
     node_1.add(new DefaultMutableTreeNode("yellow"));
    add(node_1);
    node_1 = new DefaultMutableTreeNode("sports");
     node_1.add(new DefaultMutableTreeNode("basketball"));
     node_1.add(new DefaultMutableTreeNode("soccer"));
     node_1.add(new DefaultMutableTreeNode("football"));
     node_1.add(new DefaultMutableTreeNode("hockey"));
    add(node_1);
    node_1 = new DefaultMutableTreeNode("food");
     node_1.add(new DefaultMutableTreeNode("hot dogs"));
     node_1.add(new DefaultMutableTreeNode("pizza"));
     node_1.add(new DefaultMutableTreeNode("ravioli"));
     node_1.add(new DefaultMutableTreeNode("bananas"));
    add(node_1);
   }
  };

DefaultTreeModel dem =new DefaultTreeModel(dft);
  tree.setModel(dem);

三、将tree加入滚动条

scrollPane.setViewportView(tree);

完成之后是该模型

JAVA GUI界面编程实现树节点的事件监听_第1张图片

实现监听就需要进行如下操作:

为Tree的对象添加addTreeSelectionListener事件监听,通过node.toString()获取节点名,具体代码:

tree.addTreeSelectionListener(new TreeSelectionListener() {
   public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (node == null) {
     return;
    }
    if (node.toString().equals("colors")) {
     JOptionPane.showMessageDialog(contentPane, "点中了cloors节点", "OK", JOptionPane.INFORMATION_MESSAGE);
    }
   }
  });

结果:

JAVA GUI界面编程实现树节点的事件监听_第2张图片

你可能感兴趣的:(java学习笔记)