TreesDemo

2831 단어 데이터 구조swing
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

class Branch {
	DefaultMutableTreeNode r;

	//DefaultMutableTreeNode             ,           。
	public Branch(String[] data) {
		r = new DefaultMutableTreeNode(data[0]);
		for (int i = 1; i < data.length; i++)
			r.add(new DefaultMutableTreeNode(data[i]));
		//   r       
	}

	public DefaultMutableTreeNode node() {//    
		return r;
	}
}

public class TreesDemo extends JPanel {
	private static final long serialVersionUID = 1L;
	String[][] data = { { "Colors", "Red", "Blue", "Green" }, { "Flavors", "Tart", "Sweet", "Bland" }, { "Length", "Short", "Medium", "Long" },
			{ "Volume", "High", "Medium", "Low" }, { "Temperature", "High", "Medium", "Low" }, { "Intensity", "High", "Medium", "Low" } };
	static int i = 0; //I           
	DefaultMutableTreeNode root, child, chosen;
	JTree tree;
	DefaultTreeModel model;

	public TreesDemo() {
		setLayout(new BorderLayout());
		root = new DefaultMutableTreeNode("root");
		//        
		tree = new JTree(root);
		//      ,      root  
		add(new JScrollPane(tree));
		//        Trees 
		model = (DefaultTreeModel) tree.getModel();
		//      DefaultTreeModel
		JButton test = new JButton("Press me");
		//  test     
		test.addActionListener(new ActionListener() {
			//  test     
			public void actionPerformed(ActionEvent e) {
				if (i < data.length) {
					//  test       data   
					child = new Branch(data[i++]).node();
					//     
					chosen = (DefaultMutableTreeNode)
					//  child    
					tree.getLastSelectedPathComponent();
					if (chosen == null)
						chosen = root;
					model.insertNodeInto(child, chosen, 0);
					// child   chosen
				}
			}
		});
		test.setBackground(Color.blue);
		//  test        
		test.setForeground(Color.white);
		//  test        
		JPanel p = new JPanel();
		//  p   
		p.add(test);
		//        p 
		add(p, BorderLayout.SOUTH);
		//   p   Trees 
	}

	public static void main(String args[]) {
		JFrame jf = new JFrame("JTree demo");

		jf.getContentPane().add(new TreesDemo(), BorderLayout.CENTER);
		// Trees     JFrame     
		jf.setSize(200, 500);
		jf.setVisible(true);
	}
}

좋은 웹페이지 즐겨찾기