可以给树模型对象添加事件监听器,监听节点添加,删除,修改等事件。
TreeModelEvent
public TreeModelEvent(Object source,Object[] path ,int[] childIndices, Object[] children)
参数:
source - 对生成该事件负责的 Object(事件对象的创建者通常传递 this 作为其值)
path - 指定到达已修改项父级的路径的 Object 数组,该数组的第一个元素是存储在根节点上的 Object,最后一个元素是存储在父节点上的 Object
引必须按存储顺序排列,从最低索引到最高索引
children - 包含已插入、移除或更改对象的 Object 数组childIndices - 指定已移除项的索引值的 int 数组。索
1.节点添加
通过树模型对象进行节点添加,触发事件,对于通过节点进行添加的方式,需要手动触发事件。通过树模型对象的nodesWereInserted方法进行触发,参数为添加节点的父节点和添加节点在父节点的索引数组。
2.节点修改
在对节点进行两次单击,不是双击(展开或折叠),两次单击时间比较短,会触发事件。如果通过节点进行修改,需要通过树模型对象的nodesChanged方法进行触发。
3.节点删除
触发事件后,可以通过事件对象获得被删除的节点对象数组。
演示代码如下:
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.border.TitledBorder;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class CopeTree extends JFrame
{
public JTree tree;
public DefaultTreeModel dtm;
static int index = 0;
JTextField jtf ;
public CopeTree()
{
JPanel panel = new JPanel();
initTree();
add(tree);
tree.setBorder(new TitledBorder("普通树控件"));
jtf = new JTextField(10);
jtf.addActionListener(event->{
addNode();
});
panel.add(jtf);
JButton jbn_add = new JButton("添加节点");
jbn_add.addActionListener(event -> {
addNode();
}
);
JButton jbn_adds = new JButton("添加节点s");
jbn_adds.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
node.insert(new DefaultMutableTreeNode("hello") , node.getChildCount());
System.out.println(node.getChildCount());
node.insert(new DefaultMutableTreeNode("world") , node.getChildCount());
System.out.println(node.getChildCount());
tree.updateUI();
dtm.nodesWereInserted(node, new int[] {node.getChildCount()-2,node.getChildCount()-1});
}
});
JButton jbn_del = new JButton("delete节点s");
jbn_del.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if(node.isRoot()) return;
dtm.removeNodeFromParent(node);
}
});
JButton jbn_edit = new JButton("edit节点");
jbn_edit.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
((DefaultMutableTreeNode)node.getChildAt(0)).setUserObject("hello java");
((DefaultMutableTreeNode)node.getChildAt(1)).setUserObject("hello swing");
dtm.nodesChanged(node, new int[] {0,1});
}
});
panel.add(jbn_add);
panel.add(jbn_adds);
panel.add(jbn_del);
panel.add(jbn_edit);
add(panel, BorderLayout.SOUTH);
init();
}
private void addNode()
{
String text = jtf.getText();
if (text == null || text.equals("") || text.trim().equals(""))
{
JOptionPane.showMessageDialog(this, "节点名称不能为空");
return;
}
DefaultMutableTreeNode tmtn = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (tmtn != null)
{
boolean result = isfindNode(tmtn, text);
if (result)
{
JOptionPane.showMessageDialog(this, "存在相同节点"+text);
jtf.requestFocus();
jtf.selectAll();
return;// 存在相同节点
}
DefaultMutableTreeNode t = new DefaultMutableTreeNode(text);
//tmtn.add(t);
dtm.insertNodeInto(t, tmtn, tmtn.getChildCount());
//dtm.nodesWereInserted(t, childIndices);
jtf.setText("");
scrollToNode(t);
}
else
{
JOptionPane.showMessageDialog(this, "没有选择节点");
return;
}
}
//转到新添加的节点
private void scrollToNode(DefaultMutableTreeNode t)
{
//TreeNode[] tns = dtm.getPathToRoot(t);
TreeNode[] tns = t.getPath();
TreePath tp = new TreePath(tns);
tree.scrollPathToVisible(tp);
tree.setSelectionPath(tp);//当前选择的是tns的父节点,需要tns被选择
tree.updateUI();
}
private boolean isfindNode(DefaultMutableTreeNode dmtn, String text)
{
if(dmtn.getChildCount()==0)
return false;
int count = dmtn.getChildCount();
for(int i=0;i<count;i++)
{
DefaultMutableTreeNode t = (DefaultMutableTreeNode) dmtn.getChildAt(i);
String str = (String) t.getUserObject();
if(text.equals(str))
return true;
}
return false;
}
private void initTree()
{
// TODO Auto-generated method stub
DefaultMutableTreeNode root = new DefaultMutableTreeNode("科学");
DefaultMutableTreeNode shuxue = new DefaultMutableTreeNode("数学");
DefaultMutableTreeNode jisuanji = new DefaultMutableTreeNode("计算机");
root.add(shuxue);
root.add(jisuanji);
addTreeNode(shuxue,new String[] {"数论","几何","代数"});
addTreeNode(jisuanji,new String[] {"编程语言","操作系统","算法"});
tree = new JTree(root);
tree.setEditable(true);
//tree.setDragEnabled(true);
dtm = (DefaultTreeModel) tree.getModel();
dtm.addTreeModelListener(new TreeModelListener()
{
@Override
public void treeStructureChanged(TreeModelEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void treeNodesRemoved(TreeModelEvent e)
{
// TODO Auto-generated method stub
Object[] objs = e.getChildren();
for(int i=0;i<objs.length;i++)
{
TreeNode tn = (TreeNode) objs[i];
System.out.println(tn);
}
}
@Override
public void treeNodesInserted(TreeModelEvent e)
{
copeNodes(e);
}
@Override
public void treeNodesChanged(TreeModelEvent e)
{
// TODO Auto-generated method stub
copeNodes(e);
}
});
tree.addMouseMotionListener(new MouseMotionListener()
{
@Override
public void mouseMoved(MouseEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
}
});
}
protected void copeNodes(TreeModelEvent e)
{
Object[] objs = e.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) objs[objs.length-1];
int[] num = e.getChildIndices();
for(int i=0;i<num.length;i++)
{
System.out.println(node.getChildAt(num[i]));
}
}
private void addTreeNode(DefaultMutableTreeNode parent, String[] strs)
{
for(int i = 0;i<strs.length;i++)
{
DefaultMutableTreeNode temp = new DefaultMutableTreeNode(strs[i]);
parent.add(temp);
}
}
//对树控件进行初始化,例如图标
private void setTree()
{
//tree.set
DefaultTreeCellRenderer dtcr = new DefaultTreeCellRenderer();
Image image = null;
try
{
image = ImageIO.read(new File("img/wenjian.png"));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image != null)
{
//缩放图片
Image image1 = image.getScaledInstance(24, 24, Image.SCALE_DEFAULT);
ImageIcon img = new ImageIcon(image1);
dtcr.setOpenIcon(img);
dtcr.setLeafIcon(img);
dtcr.setClosedIcon(img);
tree.setCellRenderer(dtcr);
}
}
public void init()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 500);
this.setLocationRelativeTo(null);
this.setTitle("树控件");
this.setVisible(true);
}
}
只是在添加、修改和删除时输出一些信息。
由于水平有限,如果有错误,请大家多多指导,提高水平,共同学习。