JAVA GUI介面程式設計實現樹節點的事件監聽
一、建立滾動條容器,將該容器新增到當前框架。(因為樹模型需要在滾動條中才能顯示完全)
JScrollPane scrollPane = new JScrollPane();
二、建立樹模型
JTree tree = new JTree();
DefaultMutableTreeNode dft =new DefaultMutableTreeNode("Jtree") {
{
DefaultMutableTreeNode node_1;
node_1 = new DefaultMutableTreeNode("colors");
node_1.add(new DefaultMutableTreeNode("blue"));
node_1.add(new DefaultMutableTreeNode("violet"));
node_1.add(new DefaultMutableTreeNode("red"));
node_1.add(new DefaultMutableTreeNode("yellow"));
add(node_1);
node_1 = new DefaultMutableTreeNode("sports");
node_1.add(new DefaultMutableTreeNode("basketball"));
node_1.add(new DefaultMutableTreeNode("soccer"));
node_1.add(new DefaultMutableTreeNode("football"));
node_1.add(new DefaultMutableTreeNode("hockey"));
add(node_1);
node_1 = new DefaultMutableTreeNode("food");
node_1.add(new DefaultMutableTreeNode("hot dogs"));
node_1.add(new DefaultMutableTreeNode("pizza"));
node_1.add(new DefaultMutableTreeNode("ravioli"));
node_1.add(new DefaultMutableTreeNode("bananas"));
add(node_1);
}
};
DefaultTreeModel dem =new DefaultTreeModel(dft);
tree.setModel(dem);
三、將tree加入滾動條
scrollPane.setViewportView(tree);
完成之後是該模型
實現監聽就需要進行如下操作:
為Tree的物件新增addTreeSelectionListener事件監聽,通過node.toString()獲取節點名,具體程式碼:
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (node == null) {
return;
}
if (node.toString().equals("colors")) {
JOptionPane.showMessageDialog(contentPane, "點中了cloors節點", "OK", JOptionPane.INFORMATION_MESSAGE);
}
}
});
結果: