private void beginActionPerformed(java.awt.event.ActionEvent evt){
//获得根节点的引用
DefaultMutableTreeNode root = (DefaultMutableTreeNode) PCTree.getModel().getRoot();
//将“新节点”添加到根节点之下
root.add(new DefaultMutableTreeNode("新节点"));
//重新显示这棵树
this.PCTree.updateUI();
}
●●●解释: beginActionPerformed 是“begin”这个按键的键盘响应事件
PCTree 是我的面板中的树。
第二个问题:
在选中的节点上添加“新节点”
private void addNewNodeActionPerformed(ActionEvent evt) {
//获得当前选中的节点,理论上应该判断一下root是不是为空,方便起见所以不判断了
DefaultMutableTreeNode root = (DefaultMutableTreeNode)PCTree.getLastSelectedPathComponent();
//将“新节点”添加到当前选中的节点之下
root.add(new DefaultMutableTreeNode("节点"));
//重新显示这棵树
this.PCTree.updateUI();
}
删除选中的节点
private void delPresentNodeActionPerformed(ActionEvent evt){
//找出当前选中的节点
DefaultMutableTreeNode presentNode= (DefaultMutableTreeNode) PCTree.getSelectionPath().getLastPathComponent();
//删除当前选中的节点
presentNode.removeFromParent();
//重新显示这棵树
this.PCTree.updateUI();
}
一个能够让“不同的叶子节点” 显示 “不同图标” 的程序示例
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.TreeModel;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
public class TreeImage extends JFrame {
DefaultTreeModel model;
JTree tree;
public TreeImage() {
super("");
setSize(300, 200);
model = createModel();
tree = new JTree(model);
tree.setCellRenderer(new MyTree());
JScrollPane jsp = new JScrollPane(tree);
getContentPane().add(jsp, BorderLayout.CENTER);
setVisible(true);
}
public DefaultTreeModel createModel() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("a");
DefaultMutableTreeNode b = new DefaultMutableTreeNode("b");
DefaultMutableTreeNode c = new DefaultMutableTreeNode("c");
root.add(b);
root.add(c);
return new DefaultTreeModel(root);
}
public static void main(String args[]) {
TreeImage ti = new TreeImage();
}
}
class MyTree extends DefaultTreeCellRenderer {
Border border = new EmptyBorder(1, 1, 1, 1);
public MyTree() {
setOpaque(true);
setBorder(border);
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
setText(value.toString());
if (sel)
setForeground(getTextSelectionColor());
else
setForeground(getTextNonSelectionColor());
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
String str = value.toString();
if (str == "a") {
this.setIcon(new ImageIcon("Add.gif"));
}
if (str == "b") {
this.setIcon(new ImageIcon("Copy.gif"));
}
if (str == "c") {
this.setIcon(new ImageIcon("Delete.gif"));
}
return this;
}
}