[英]How do I check if a file exists in Java when the file path contains chinese words in Linux?
[英]javafx: How do I create a TreeItem that displays a tooltip that contains the file path and load the file path on double click?
我試圖將包含文件路徑的工具提示附加到TreeItem<String>
,這樣當我將鼠標懸停在此TreeItem上時,當我將鼠標懸停在它上面時,它將顯示文件路徑的文本。 這在我的代碼中不起作用,因為它抱怨我無法將其安裝到String上。 我怎么解決這個問題?
其次,我希望能夠雙擊TreeItem,然后它可以自動加載文件。 我該如何實現?
@FXML
TreeView<String> fxFileTree;
public void defineFileTree(){
TreeItem<String> root = new TreeItem<String>("Portfolio");
fxFileTree.setShowRoot(true);
root.setExpanded(true);
fxFileTree.setRoot(root);
}
public void populateTree(String fileName, String filePath){
addLeaf(fileName, (TreeItem<String>) fxFileTree.getRoot(), filePath);
}
public void addLeaf(String leaf, TreeItem<String> parent, String filePath{
TreeItem<String> item = new TreeItem<>(leaf);
Tooltip.install(item,filepath) // <- This is wrong
parent.getChildren().add(item);
}
更新:此練習的目標是建立一棵僅包含根和一個分支級別的樹,即root -> leaf1
(在此處停止,沒有用於子代的孫子,僅子代)。 根將只是一個標題字符串。 我想在根部添加葉子。 葉是文件對象。 葉子的顯示文本將是文件名,並為此葉子安裝工具提示。 工具提示將顯示文件路徑。
您不能在TreeItem
上設置工具提示。 TreeItem
表示樹中顯示的數據 ,它們不是UI組件。 您需要在TreeCell
上設置工具提示,您可以在工廠中進行設置。
由於您將需要訪問有關文件的數據,因此不應該使用TreeView<String>
和TreeItem<String>
:您應該使用TreeView<File>
或TreeView<Path>
(換句話說,使數據樹的類型( File
或Path
)。 因此,您將執行以下操作:
@FXML
private TreeView<Path> fxFileTree ;
private TreeItem<Path> root ;
// ...
public void initialize() {
fxFileTree.setCellFactory(tv -> {
final Tooltip tooltip = new Tooltip();
TreeCell<Path> cell = new TreeCell<Path>() {
@Override
public void updateItem(Path item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setTooltip(null);
} else if (getTreeItem() == root) {
setText("Portfolio");
setTooltip(null);
} else {
setText(item.getFileName().toString());
tooltip.setText(item.toRealPath().toString());
setTooltip(tooltip);
}
}
};
cell.setOnMouseClicked(e -> {
if (e.getClickCount() == 2 && ! cell.isEmpty()) {
Path file = cell.getItem();
// do whatever you need with path...
}
});
return cell ;
});
}
public void defineFileTree(){
root = new TreeItem<>(null);
fxFileTree.setShowRoot(true);
root.setExpanded(true);
fxFileTree.setRoot(root);
}
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.