JTree

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class JTreeDemo3 implements TreeSelectionListener {

	JEditorPane editorPane;
	
	public JTreeDemo3(){
		JFrame jf = new JFrame();
		Container contentPane = jf.getContentPane();
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("資源管理器");
		DefaultMutableTreeNode node = new DefaultMutableTreeNode("JTreeDemo1.java");
		root.add(node);
		node = new DefaultMutableTreeNode("JTreeDemo2.java");
		root.add(node);
		node = new DefaultMutableTreeNode("JTreeDemo3.java");
		root.add(node);
		
		JTree tree = new JTree(root);
		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		tree.addTreeSelectionListener(this);
		
		JScrollPane scrollPane = new JScrollPane(tree);
		editorPane = new JEditorPane();
		JScrollPane scrollPane2 = new JScrollPane(editorPane);
		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,scrollPane,scrollPane2);
		splitPane.setOneTouchExpandable(true);
		
		contentPane.add(splitPane);
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String...args){
		new JTreeDemo3();
	}
	
	@Override
	public void valueChanged(TreeSelectionEvent e){
		JTree tree = (JTree) e.getSource();
		DefaultMutableTreeNode selectionNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
//		為什么不用JTree.getLastPathComponent();????
//		用JTree.getSelectionPath().getLastPathComponent也可以
		System.out.println(selectionNode);
		System.out.println(tree.getSelectionPath().getLastPathComponent());
		String nodeName = selectionNode.toString();
		if(selectionNode.isLeaf()){
			String filepath = "file:"+System.getProperty("user.dir")+System.getProperty("file.separator")
				+"src/com/javaswing/tree/"+nodeName;
			System.out.println(filepath);
			try{
				editorPane.setPage(filepath);
			}catch(IOException ioe){
				System.out.println("系統找不到文件");
			}
		}
	}
}


參考:深入淺出Java Swing程序設計

你可能感兴趣的:(java,swing)