当前位置: 代码迷 >> J2SE >> 请教jtree的每个节点上加上鼠标单击事件,如何加啊,用addActionListener好像不行啊
  详细解决方案

请教jtree的每个节点上加上鼠标单击事件,如何加啊,用addActionListener好像不行啊

热度:87   发布时间:2016-04-24 16:23:41.0
请问jtree的每个节点上加上鼠标单击事件,怎么加啊,用addActionListener好像不行啊?
我要建了一个jtree     ,有多个分节点,怎么给每个不同的节点上添加鼠标单击事件啊??   谢谢!!1

------解决方案--------------------
要用到TreeSelectionListener这个接口
以下是我的例子
/**
*
*/
package com.softfz.zxj;

import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

class MyTreeSelectionListener implements TreeSelectionListener{

private Object selectionObj;
private ArrayList uList;
//private ArrayList uIdList = new ArrayList();
//private JTree tree = new JTree();
private DefaultMutableTreeNode selectionNode;
public MyTreeSelectionListener(ArrayList uList){
this.uList = uList;
}
//关键是这个方法
public void valueChanged(TreeSelectionEvent e) {
// TODO 自动生成方法存根

JTree tree = (JTree)e.getSource();
selectionNode =
(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();//得到选中的节点
selectionObj = selectionNode.getUserObject();//得到该节点所存放的对象
if(selectionObj instanceof Deptinfo)
{
if(selectionNode.getChildCount()!=0)
{
String dId =((Deptinfo)selectionObj).getDeptId();
String dName = ((Deptinfo)selectionObj).getDeptName();
Client.getClient().chatUIDLabel.setText(dId);
Client.getClient().chatUnameLabel.setText(dName);
Client.getClient().portraitLabel = new JLabel(new ImageIcon( "image\\Login.gif "));
}
else
{
JOptionPane.showMessageDialog(null, "该部门无人,不能聊天! ", "出错 ",
JOptionPane.ERROR_MESSAGE);
tree.setSelectionRow(0);
}

}else if(selectionObj instanceof Userinfo)
{
Userinfo uInfo = (Userinfo)selectionObj;
String uId =uInfo.getUserId();
if(!Client.getClient().myUID.equals(uId))
{
if(uInfo.getOnline().equals( "1 "))
{
String uName = ((Userinfo)selectionObj).getUserName();
String uIcon = ((Userinfo)selectionObj).getIconNum();
Client.getClient().chatUIDLabel.setText(uId);
Client.getClient().chatUnameLabel.setText(uName);
Client.getClient().portraitLabel.setIcon(new ImageIcon( "image\\userhead\\big "+uIcon+ ".png "));
}
else
{

JOptionPane.showMessageDialog(null, "不能对没上线的人聊天! ", "出错 ",
JOptionPane.ERROR_MESSAGE);
tree.setSelectionRow(0);
}
}
else
{

JOptionPane.showMessageDialog(null, "不能对本人聊天! ", "出错 ",
JOptionPane.ERROR_MESSAGE);
tree.setSelectionRow(0);
}
}
else
{

Client.getClient().chatUIDLabel.setText( " ");
Client.getClient().chatUnameLabel.setText( "公司 ");
Client.getClient().portraitLabel.setIcon(new ImageIcon( "image\\Login.gif "));

// return uIdList;
}
}
}

------解决方案--------------------
不懂,学习学习,你可以查一下api看看Jtree支持什么事件
好像自身有这些
addTreeExpansionListener(TreeExpansionListener tel)
为 TreeExpansion 事件添加侦听器。
void addTreeSelectionListener(TreeSelectionListener tsl)
为 TreeSelection 事件添加侦听器。
void addTreeWillExpandListener(TreeWillExpandListener tel)