ããjava ä¸actionPerformedçæ¹æ³å¯ä»¥å·æ°jtreeæ ç¶å¾çï¼å
·ä½åæ³æ¯å¨actionPerformedçæ¹æ³å°¾é¨å ä¸JSPcrollPanel.updateUI();
代ç å¦ä¸:
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeDemo {
public static void main(String[] args) {
// å建没æç¶èç¹ååèç¹ãä½å
许æåèç¹çæ èç¹ï¼å¹¶ä½¿ç¨æå®çç¨æ·å¯¹è±¡å¯¹å®è¿è¡åå§åã
// public DefaultMutableTreeNode(Object userObject)
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("软件é¨");
node1.add(new DefaultMutableTreeNode(new User("å°è±")));
node1.add(new DefaultMutableTreeNode(new User("å°è")));
node1.add(new DefaultMutableTreeNode(new User("å°é¾")));
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("éå®é¨");
node2.add(new DefaultMutableTreeNode(new User("å°å¶")));
node2.add(new DefaultMutableTreeNode(new User("å°é¯")));
node2.add(new DefaultMutableTreeNode(new User("å°å¤")));
DefaultMutableTreeNode top = new DefaultMutableTreeNode("èå管ç");
top.add(new DefaultMutableTreeNode(new User("æ»ç»ç")));
top.add(node1);
top.add(node2);
final JTree tree = new JTree(top);
JFrame f = new JFrame("JTreeDemo");
f.add(tree);
f.setSize(300, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// æ·»å éæ©äºä»¶
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
.getLastSelectedPathComponent();
if (node == null)
return;
Object object = node.getUserObject();
if (node.isLeaf()) {
User user = (User) object;
System.out.println("ä½ éæ©äºï¼" + user.toString());
}
}
});
}
}
class User {
private String name;
public User(String n) {
name = n;
}
// éç¹å¨toStringï¼èç¹çæ¾ç¤ºææ¬å°±æ¯toString
public String toString() {
return name;
}
}