2014-10-02 38 views
1

我對樹視圖中的下列cellValueFactory添加文本菜單和dragAndDrop功能:僅顯示contextMenu當用戶右鍵點擊一個項目

treeView.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() { 
     @Override 

     public TreeCell<String> call(TreeView<String> stringTreeView) { 
      TreeCell<String> treeCell = new TreeCell<String>() { 
       @Override 

       protected void updateItem(String item, boolean empty) { 
        super.updateItem(item, empty); 
        if (!empty && item != null) { 
         setText(item); 
         setGraphic(getTreeItem().getGraphic()); 

         final ContextMenu contextMenu = new ContextMenu(); 

         MenuItem item2 = new MenuItem("Delete"); 
         item2.setOnAction(new EventHandler<ActionEvent>() { 
          public void handle(ActionEvent e) { 
           System.out.println("Here I will add some delete functionality"); 
          } 
         }); 
         contextMenu.getItems().addAll(item2); 

         treeView.setContextMenu(contextMenu); 

         setContextMenu(contextMenu); 

        } else { 
         setText(null); 
         setGraphic(null); 

        } 
       } 
      }; 

      addDragAndDrop(treeCell); 
      treeView.setEditable(true); 
      return treeCell; 
     } 

    }); 

拖放的偉大工程和文本菜單顯示出來,但它表明在樹狀視圖中右擊一切。我怎麼才能讓它只出現在用戶實際上右鍵單擊樹形視圖中的一個項目時?

+0

將上下文菜單添加到單元格而不是樹。 – 2014-10-02 09:35:57

+0

您可以將它作爲答案發布,我會接受它。再次感謝@james_D :) – miniHessel 2014-10-02 09:44:11

回答

1

您正在設置TreeViewTreeCell上的上下文菜單。只需將其設置在TreeCell。另外,您應該在單元格爲空的情況下將其刪除:

  protected void updateItem(String item, boolean empty) { 
       super.updateItem(item, empty); 
       if (!empty && item != null) { 
        setText(item); 
        setGraphic(getTreeItem().getGraphic()); 

        final ContextMenu contextMenu = new ContextMenu(); 

        MenuItem item2 = new MenuItem("Delete"); 
        item2.setOnAction(new EventHandler<ActionEvent>() { 
         public void handle(ActionEvent e) { 
          System.out.println("Here I will add some delete functionality"); 
         } 
        }); 
        contextMenu.getItems().addAll(item2); 

        // remove this line: 
        //treeView.setContextMenu(contextMenu); 

        setContextMenu(contextMenu); 

       } else { 
        setText(null); 
        setGraphic(null); 

        setContextMenu(null); 
       } 
      } 
相關問題