gpt4 book ai didi

java - JTree 随着 arraylist 的变化动态更新

转载 作者:行者123 更新时间:2023-11-30 02:53:25 25 4
gpt4 key购买 nike

我寻找答案,但找不到任何东西来解决这个问题。我有两个数组列表,其中包含在用户单击后动态更改的字符串,现在创建将显示一个列表中的元素的 JTree 取决于另一个列表中的某种类型。我有一个问题,因为我总是在列表中添加和删除某些内容,并且需要 JTree 来显示更改。它将正确添加 List 中的所有元素,直到我展开,之后就不可能更新 JTree 的内容,至少对我来说是这样。如果我清空我的列表,它会显示为折叠的,但所有内容仍然显示为展开的,即使它在控制台中给出子计数为 0,如果我向列表中添加某些内容,它会添加它但不会显示它。所以基本上问题是直观地显示JTree的变化。

public class JSelectedTree extends JPanel{
private JTree selectionTree;
private DefaultTreeModel treeModel;
public DefaultMutableTreeNode point;
public DefaultMutableTreeNode polygon;
public DefaultMutableTreeNode line;
public JSelectedTree() {
initGUI();
}

public void initGUI() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
point = new DefaultMutableTreeNode("Point");
polygon = new DefaultMutableTreeNode("Polygon");
line = new DefaultMutableTreeNode("Line");
root.add(point);
root.add(polygon);
root.add(line);
treeModel = new DefaultTreeModel(root);
selectionTree = new JTree(root);
selectionTree.setRootVisible(false);
selectionTree.setShowsRootHandles(false);
selectionTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
JScrollPane scroll = new JScrollPane(selectionTree);
scroll.setBorder(BorderFactory.createTitledBorder("Selected"));
setLayout(new BorderLayout());
add(scroll, BorderLayout.CENTER);
}
public void resetTree(){
if(!MultiSelectTool.selectedObject.isEmpty()){
polygon.removeAllChildren();
point.removeAllChildren();
line.removeAllChildren();
treeModel.reload();
int n = MultiSelectTool.selectedObject.size();
for(int i = 0; i < n; i++){
if(MultiSelectTool.selectedCoords.get(i).contains("(((")){
DefaultMutableTreeNode child = new DefaultMutableTreeNode(MultiSelectTool.selectedObject.get(i));
treeModel.insertNodeInto(child, polygon, polygon.getChildCount());
}else if(MultiSelectTool.selectedCoords.get(i).contains("((")){
DefaultMutableTreeNode child = new DefaultMutableTreeNode(MultiSelectTool.selectedObject.get(i));
treeModel.insertNodeInto(child, line, line.getChildCount());
}else{
DefaultMutableTreeNode child = new DefaultMutableTreeNode(MultiSelectTool.selectedObject.get(i));
treeModel.insertNodeInto(child, point, point.getChildCount());
}
}
}else{
polygon.removeAllChildren();
point.removeAllChildren();
line.removeAllChildren();
treeModel.reload();
}
}
}

最佳答案

尝试使用 MVC 模式,以便可以更新 View :)

关于java - JTree 随着 arraylist 的变化动态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967989/

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