gpt4 book ai didi

java - 使用路径检查 JTree 节点是否存在

转载 作者:搜寻专家 更新时间:2023-11-01 01:36:42 26 4
gpt4 key购买 nike

我有一个经典的 JTree 填充了一些点头。让我们假设树看起来像这样:

Root
|-Fruit
|--Apple
|--Orange
|-Objects
|--Table
|--Car

Java 中是否有任何方法可以使用这样的假定路径检查节点是否存在:

TreeNode found = model.getNodeOrNull("\\Fruit\\Apple")

因此,如果给定位置的节点存在,则返回它,如果不存在,则返回 null? Java有没有这样的机制?

最佳答案

您可以按照这些思路尝试一些东西。

Tree Node Location

示例输出

food:pizza found true
od:pizza found false
sports:hockey found true
sports:hockey2 found false

TreeNodeLocation.java

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.Position;
import javax.swing.tree.TreePath;

public class TreeNodeLocation {

private JTree tree = new JTree();

TreeNodeLocation() {
JPanel p = new JPanel(new BorderLayout(2,2));

final JTextField find = new JTextField("food:pizza");
find.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
boolean found = findText(find.getText());
System.out.println(find.getText() + " found " + found);
}
});
p.add(find, BorderLayout.PAGE_START);

tree.setVisibleRowCount(8);
for (int row=tree.getRowCount(); row>=0; row--) {
tree.expandRow(row);
}

p.add(new JScrollPane(tree),BorderLayout.CENTER);

JOptionPane.showMessageDialog(null, p);
}

public boolean findText(String nodes) {
String[] parts = nodes.split(":");
TreePath path = null;
for (String part : parts) {
int row = (path==null ? 0 : tree.getRowForPath(path));
path = tree.getNextMatch(part, row, Position.Bias.Forward);
if (path==null) {
return false;
}
}
tree.scrollPathToVisible(path);
tree.setSelectionPath(path);

return path!=null;
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TreeNodeLocation();
}
});
}
}

关于java - 使用路径检查 JTree 节点是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10883293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com