树形控件单击某选项时如何响应啊?

我做了一个最简单的树形结构,在向里面添加消息响应的时候竟然是对整个控件反应的,要怎么样才能对单独的选项有不同的反应呢?... 我做了一个最简单的树形结构,在向里面添加消息响应的时候竟然是对整个控件反应的,要怎么样才能对单独的选项有不同的反应呢? 展开
 我来答
创作者Q7henbfAMF
2010-04-03 · 超过58用户采纳过TA的回答
知道小有建树答主
回答量:116
采纳率:0%
帮助的人:158万
展开全部
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class SimpleTree extends JFrame {

JTree tree;
DefaultTreeModel treeModel;

public SimpleTree( ) {
super("Tree Test Example");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void init( ) {
// Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because the
// DefaultTreeModel can use it to build a complete tree.
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");

// Build our tree model starting at the root node, and then make a JTree out
// of it.
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);

// Build the tree up from the nodes we created.
treeModel.insertNodeInto(subroot, root, 0);
// Or, more succinctly:
subroot.add(leaf1);
root.add(leaf2);

// Display it.
getContentPane( ).add(tree, BorderLayout.CENTER);

final JLabel messageLabel = new JLabel("Nothing selected.");
add(messageLabel, BorderLayout.SOUTH);

//添加监听器啊
tree.addTreeSelectionListener(new TreeSelectionListener( ) {
public void valueChanged(TreeSelectionEvent tse) {
TreePath tp = tse.getNewLeadSelectionPath( );

//处理事件啊
messageLabel.setText("Selected: " + tp.getLastPathComponent( ));
}
});

}

public static void main(String args[]) {
SimpleTree tt = new SimpleTree( );
tt.init( );
tt.setVisible(true);
}
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式