如何使用JavaFX从树视图中的绝对路径获取文件夹或文件名



itemlist.java::

public class itemlist {
public TreeItem<File> createNode(final File f) {
return new TreeItem<File>(f) {
private boolean isLeaf;
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;`
@Override
public ObservableList<TreeItem<File>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
super.getChildren().setAll(buildChildren(this));
}
return super.getChildren();
}
@Override
public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
File f = (File) getValue();
isLeaf = f.isFile();
}
return isLeaf;
}
private ObservableList<TreeItem<File>> buildChildren(
TreeItem<File> TreeItem) {
File f = TreeItem.getValue();
if (f == null) {
return FXCollections.emptyObservableList();
}
if (f.isFile()) {
return FXCollections.emptyObservableList();
}
File[] files = f.listFiles();
// String allfiles= files.toString();
//allfiles.
if (files != null) {
ObservableList<TreeItem<File>> children = FXCollections
.observableArrayList();
for (File childFile : files) {
children.add(createNode(childFile));
}
return children;
}
return FXCollections.emptyObservableList();
}

controller.java:::

public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub

itemlist obj=new itemlist();
TreeItem<File> rt =obj.createNode(new File("c:\"));
fileView.setRoot(rt);`

这给了我一个输出C:\programfiles ->C:\programfilesjava ->C:\programfilespython我只想删除这些绝对路径&只需游戏文件/文件夹名称。我知道使用getName会有所帮助,但我如何在代码中实现getName((?

您可以将泛型类型从File更改为String,并且只使用文件名:

class ItemList {

public TreeItem<String> createNode(final File f) {
return new TreeItem<String>(f.getName()) {
private boolean isLeaf;
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;

@Override
public ObservableList<TreeItem<String>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
super.getChildren().setAll(buildChildren(f));
}
return super.getChildren();
}

@Override
public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
isLeaf = f.isFile();
}
return isLeaf;
}

private ObservableList<TreeItem<String>> buildChildren(
File f) {

if (f == null) {
return FXCollections.emptyObservableList();
}
if (f.isFile()) {
return FXCollections.emptyObservableList();
}
File[] files = f.listFiles();

if (files != null) {
ObservableList<TreeItem<String>> children = FXCollections
.observableArrayList();
for (File childFile : files) {
children.add(createNode(childFile));
}
return children;
}
return FXCollections.emptyObservableList();
}
};
}
}
ItemList obj = new ItemList();
TreeItem<String> rt = obj.createNode(new File("/"));
TreeView<String> treeView = new TreeView<>(rt);

相关内容

  • 没有找到相关文章

最新更新