第一步给JList添加鼠标事件:jList1.addMouseListener(listMouseAdapter);
MouseAdapter listMouseAdapter = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(jList1.getSelectedIndex() != -1) {
if (e.getClickCount() == 1)
{
oneClick(jList1.getSelectedValue());
}
if(e.getClickCount() == 2){
twoClick(jList1.getSelectedValue());
}
}
}
};
/**
* 单击处理
* @param value
*/
private void oneClick(Object value)
{
expandSelect(jTree1, new TreePath(rootNode), true, value.toString());
}
/**
* 双击处理
* @param value
*/
private void twoClick(Object value)
{
collapseAll(jTree1, new TreePath(rootNode), false, value.toString());
jTree1.expandPath(new TreePath(rootNode));
}
实现单击打开所选当前列表的在tree中的数据
实现双击关闭所选当前列表的在tree中的数据
* 展开选择枝干
*
* @param tree
* @param parent
* @param expand
* @param str
*/
private void expandSelect(JTree tree, TreePath parent, boolean expand, String str)
{
TreeNode node = (TreeNode) parent.getLastPathComponent();
if (node.getChildCount() > 0)
{
for (Enumeration e = node.children(); e.hasMoreElements();)
{
TreeNode n = (TreeNode) e.nextElement();
if(n.toString().equals(str)){
TreePath path = parent.pathByAddingChild(n);
expandSelect(tree, path, expand, str);
}
}
}
if (expand)
{
tree.expandPath(parent);
} else
{
tree.collapsePath(parent);
}
}
/**
* 关闭选择枝干
*
* @param tree
* @param parent
* @param expand
* @param str
*/
private void collapseAll(JTree tree, TreePath parent, boolean expand, String str)
{
TreeNode node = (TreeNode) parent.getLastPathComponent();
if (node.getChildCount() > 0)
{
for (Enumeration e = node.children(); e.hasMoreElements();)
{
TreeNode n = (TreeNode) e.nextElement();
if(n.toString().equals(str)){
TreePath path = parent.pathByAddingChild(n);
parent.getPath();
collapseAll(tree, path, expand, str);
}
}
}
if (expand)
{
tree.expandPath(parent);
} else
{
tree.collapsePath(parent);
}
}