2014-07-28 16:52:33

JavaSwing Jtree 自定义node(选中节点获取自定义节点信息)

如果选中一个节点直接通过node的text去获取很多时候是不行的,最简单的办法是继承DefaultMutableTreeNode类,重写toString和构造方法。
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeActionMap extends JFrame{
	private static final long serialVersionUID = 1L;
	public static void main(String[] args) {
		JFrame j = new JFrame("Test");
		j.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		j.setSize(500, 300);
		j.setLocation(500, 300);
		NodeBean root = new NodeBean("用户列表");
		root.add(new NodeBean(1, "admin"));
		root.add(new NodeBean(2, "root"));
		root.add(new NodeBean(3, "test"));
		final JTree t = new JTree(root);
		t.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
            	NodeBean n = (NodeBean)t.getLastSelectedPathComponent();
                System.out.println(n.getId());
            }
        });
		j.add(t);
		j.setVisible(true);
	}
}
class NodeBean extends DefaultMutableTreeNode{
	private static final long serialVersionUID = 1L;
	private int id;
	private String user;
	public NodeBean(int id, String user) {
		super();
		this.id = id;
		this.user = user;
	}
	public NodeBean(Object obj){
        super(obj);
    }
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String toString(){
		return (String) (super.userObject!=null?super.userObject:this.user);
	}
}
发表回复