java树组件

package 树组件;

import java.awt.Component;

public class Example9_12 {

	public static void main(String args[]){
		TreeWin win=new TreeWin();
		win.setTitle("树组件");
	}

}
package 树组件;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class TreeWin extends JFrame implements TreeSelectionListener,ActionListener{
	JTree tree;
	JTextArea showText;
	TreeWin(){
		setLayout(new FlowLayout());
		DefaultMutableTreeNode root=new DefaultMutableTreeNode("商品");
		DefaultMutableTreeNode nodeTV=new DefaultMutableTreeNode("电视机类");
		DefaultMutableTreeNode nodePhone=new DefaultMutableTreeNode("手机类");
		DefaultMutableTreeNode tv1=new DefaultMutableTreeNode(new Goods("长虹电视",5699));
		DefaultMutableTreeNode tv2=new DefaultMutableTreeNode(new Goods("海尔电视",7832));
		DefaultMutableTreeNode phone1=new DefaultMutableTreeNode(new Goods("诺基亚手机",7320));
		DefaultMutableTreeNode phone2=new DefaultMutableTreeNode(new Goods("小米手机",7882));
		DefaultMutableTreeNode phone3=new DefaultMutableTreeNode(new Goods("三星手机",7302));
		root.add(nodeTV);
		root.add(nodePhone);
		nodeTV.add(tv1);
		nodeTV.add(tv2);
		nodePhone.add(phone1);
		nodePhone.add(phone2);
		nodePhone.add(phone3);
		tree=new JTree(root);
		tree.addTreeSelectionListener(this);
		showText=new JTextArea();
		setLayout(new GridLayout(1,3));
		add(new JScrollPane(tree));
		add(new JScrollPane(showText));
		JButton button=new JButton("确定");
		add(button);
		button.addActionListener(this);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		setBounds(80,80,300,300);
		validate();
	}
	public void actionPerformed(ActionEvent e){
		int n=JOptionPane.showConfirmDialog(this, "确定要关闭吗?","确认对话框",JOptionPane.YES_NO_CANCEL_OPTION);
		if(n==JOptionPane.YES_OPTION){
			dispose();
		}
	}
	public void valueChanged(TreeSelectionEvent e){
		DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
		if(node.isLeaf()){
			Goods s=(Goods)node.getUserObject();
			showText.append(s.name+","+s.price+"元\n");
		}
		else
			showText.setText(null);
	}
}

package 树组件;

public class Goods {
	String name;
	double price;
	Goods(String n,double s){
		name=n;
		price=s;
	}
	public String toString(){
		return name;
	}
}

这是运行结果:

java树组件_第1张图片


你可能感兴趣的:(java树组件)