gpt4 book ai didi

java - JTree 创建新文件使其被选中

转载 作者:太空宇宙 更新时间:2023-11-04 08:52:26 24 4
gpt4 key购买 nike

我想让它就像当我单击按钮时,它会创建一个新文件。然后 jTree 将突出显示新文件。下面是我的代码。目前我创建新文件,我将显示新文件但不突出显示该文件。

class FileTreeModel implements TreeModel {
private FileNode root;

public FileTreeModel(String directory) {
root = new FileNode(directory);
}

public Object getRoot() {
return root;
}

public Object getChild(Object parent, int index) {
FileNode parentNode = (FileNode) parent;
return new FileNode(parentNode, parentNode.listFiles()[index].getName());
}

public int getChildCount(Object parent) {
FileNode parentNode = (FileNode) parent;
if (parent == null || !parentNode.isDirectory()
|| parentNode.listFiles() == null) {
return 0;
}

return parentNode.listFiles().length;
}

public boolean isLeaf(Object node) {
return (getChildCount(node) == 0);
}

public int getIndexOfChild(Object parent, Object child) {
FileNode parentNode = (FileNode) parent;
FileNode childNode = (FileNode) child;

return Arrays.asList(parentNode.list()).indexOf(childNode.getName());
}

public void valueForPathChanged(TreePath path, Object newValue) {

}

public void addTreeModelListener(TreeModelListener l) {
}

public void removeTreeModelListener(TreeModelListener l) {
}

}

class FileNode extends java.io.File {

public FileNode(String directory) {
super(directory);
}

public FileNode(FileNode parent, String child) {
super(parent, child);
}

@Override
public String toString() {
return getName();

}

}

       jTree = new JTree();
jTree.setBounds(new Rectangle(164, 66, 180, 421));
jTree.setBackground(SystemColor.inactiveCaptionBorder);
jTree.setBorder(BorderFactory.createTitledBorder(null, "",
TitledBorder.LEADING, TitledBorder.TOP, new Font("Arial",
Font.BOLD, 12), new Color(0, 0, 0)));
FileTreeModel model = new FileTreeModel(root);
jTree.setRootVisible(false);
jTree.setModel(model);
expandAll(jTree);

public void expandAll(JTree tree) {

int row = 0;
while (row < tree.getRowCount()) {
tree.expandRow(row);
row++;
}
}

最佳答案

您可以通过调用JTree.setSelectionPath(TreePath path)来做到这一点;

关于java - JTree 创建新文件使其被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3046351/

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