2015-04-20 53 views
0

我有一個帶有上下文菜單的TreeView,除了樹爲空時以外的所有作品。當樹爲空時,我想阻止用戶顯示上下文菜單。當樹爲空時,JavaFX TreeView隱藏上下文菜單

//Set up context menu and menu items 
final ContextMenu contextMenu = new ContextMenu(); 
final MenuItem miSubir = new MenuItem("Subir"); 
final MenuItem miBajar = new MenuItem("Bajar"); 
final MenuItem miBorrar = new MenuItem("Borrar"); 

//add events from clic on menu items 
miBorrar.setOnAction((ActionEvent event) -> { 
    ... 
}); 

... 

//Add menu items to context menu 
contextMenu.getItems().add(miSubir); 
contextMenu.getItems().add(miBajar); 
contextMenu.getItems().add(miBorrar); 

//Associate context menu to treeview 
treeEjercicios.setContextMenu(contextMenu); 

當我使用Table組件,我解決的問題:

row.contextMenuProperty().bind(
     Bindings.when(row.emptyProperty()) 
     .then((ContextMenu) null) 
     .otherwise(contextMenu) 
); 

但我不知道如何應用與樹視圖或任何其他替代使用?

+1

我會嘗試用treeCell相同的(如果你已經提供了SSCCE ;-) – kleopatra

回答

0

如果顯示根項目,即tree.setShowRoot(true),則可以假設當根項目爲空時樹視圖爲空。因此,我們可以將其綁定

tree.contextMenuProperty().bind(
     Bindings.when(Bindings.isNull(tree.rootProperty())) 
     .then((ContextMenu) null) 
     .otherwise(contextMenu) 
); 

否則,如果根項目沒有顯示,則該樹可以認爲是空的,如果這根項目一直沒有孩子,即當isLeaf()返回true。在這種情況下,綁定將是:

tree.contextMenuProperty().bind(
     Bindings.when(tree.getRoot().leafProperty()) 
     .then((ContextMenu) null) 
     .otherwise(contextMenu) 
); 
+0

顯然,這是行不通的。不,根目錄是隱藏的,因爲我不想在UI中顯示。 – Marcos

+0

@Marcos請參閱更新。 –