import java.awt.BorderLayout;
import java.nio.file.Paths;
import javax.swing.JFrame;
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;
import javax.swing.tree.TreeSelectionModel;
public class Tree extends JFrame{
public Tree(){//构造方法
DefaultMutableTreeNode root=new DefaultMutableTreeNode("根节点");
DefaultMutableTreeNode nodeFirst=new DefaultMutableTreeNode("一级子节点A");
root.add(nodeFirst);//将一级节点添加到根节点
//创建不允许有子节点的二级节点
DefaultMutableTreeNode nodeSecond=new DefaultMutableTreeNode("二级子节点",false);
nodeFirst.add(nodeSecond);
root.add(new DefaultMutableTreeNode("一级子节点B"));
JTree treeRoot=new JTree(root);//利用根节点直接创建树
getContentPane().add(treeRoot,BorderLayout.WEST);
//利用根节点创建树模型,采用默认的判断方式
DefaultTreeModel treeModelDefault=new DefaultTreeModel(root);
JTree treeDefault=new JTree(treeModelDefault);
getContentPane().add(treeDefault, BorderLayout.CENTER);
//利用根节点创建树模型并采用非默认的判断方式
DefaultTreeModel treeModelPointed=new DefaultTreeModel(root,true);
JTree treePointed=new JTree(treeModelPointed);
getContentPane().add(treePointed, BorderLayout.EAST);
TreeSelectionModel treeSelectionModel=treeRoot.getSelectionModel();//获得树的选择模型
treeSelectionModel.setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);//设置为连选
treeRoot.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent e){
if(!treeRoot.isSelectionEmpty()){
TreePath[] selectionPaths=treeRoot.getSelectionPaths();//获得所有被选中节点路径的数组
for(int i=0;i<selectionPaths.length;i++){
TreePath treePath=selectionPaths[i];
//以数组的形式返回路径中所有节点的对象
Object[] path=treePath.getPath();
for(int j=0;j<path.length;j++){
DefaultMutableTreeNode node=(DefaultMutableTreeNode)path[j];
System.out.print(node.getUserObject()+(j==(path.length-1)?"":"-->"));
}
System.out.println();
}
System.out.println();
}
}
});
setSize(350,100);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Tree();
}
}
树的创建及点击事件Java
最新推荐文章于 2022-08-16 14:05:03 发布