java swing 树_Java Swing - 如何展开所选的树路径

import java.util.HashMap;

import java.util.Stack;

import javax.swing.Box;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreePath;

public class Main extends Box {

public Main() {

super(BoxLayout.Y_AXIS);

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

for (int i = 0; i < 14; i++) {

DefaultMutableTreeNode node = new DefaultMutableTreeNode("Root" + i);

node.add(new DefaultMutableTreeNode("Child" + i));

root.add(node);

}

CustomTree tree = new CustomTree(root);

tree.setRootVisible(false);

JScrollPane pane = new JScrollPane(tree);

add(pane);

JButton button = new JButton("Expand");

button.addActionListener(e-> tree.expandSelectedPaths());

add(button);

}

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setContentPane(new Main());

frame.validate();

frame.pack();

frame.setVisible(true);

}

}

class CustomTree extends JTree {

HashMap expandedState = new HashMap();

Stack s = new Stack();

public CustomTree(DefaultMutableTreeNode root) {

super(root);

}

public void expandSelectedPaths() {

TreePath[] paths = getSelectionPaths();

if(paths == null || paths.length == 0){

return;

}

setSelectionPath(paths[0]);

for (TreePath path : paths) {

TreePath parentPath = path.getParentPath();

while (parentPath != null) {

if (isExpanded(parentPath)) {

parentPath = null;

} else {

s.push(parentPath);

parentPath = parentPath.getParentPath();

}

}

for (int i = s.size() - 1; i >= 0; i--) {

parentPath = s.pop();

if (!isExpanded(parentPath)) {

expandedState.put(parentPath, Boolean.TRUE);

}

}

}

if (accessibleContext != null) {

((AccessibleJTree) accessibleContext).fireVisibleDataPropertyChange();

}

for (TreePath path : paths) {

fireTreeExpanded(path);

try {

fireTreeWillExpand(path);

} catch (Exception eve) {

return;

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值