2014-11-08 70 views
3

我有一個JavaFX ContextMenu分配給鼠標右鍵單擊一個滾動窗格。它會打開,但在滾動窗格外單擊時它不會關閉。我可以將另一個鼠標事件添加到滾動窗格以隱藏它,但這隻能解決1個問題。主要的問題是,當我點擊滾動窗格的任何組件時,上下文菜單保持打開狀態。JavaFX ContextMenu不會自動隱藏

示例:點擊鼠標右鍵打開彈出窗口,然後點擊按鈕。彈出菜單仍處於打開狀態。

import javafx.application.Application; 
import javafx.event.EventHandler; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.ContextMenu; 
import javafx.scene.control.MenuItem; 
import javafx.scene.control.ScrollPane; 
import javafx.scene.input.MouseEvent; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 

public class Main extends Application { 

    public static void main(String[] args) { 
     launch(args); 
    } 

    @Override 
    public void start(Stage primaryStage) { 

     final ContextMenu contextMenu = new ContextMenu(); 

     MenuItem item1 = new MenuItem("About"); 
     MenuItem item2 = new MenuItem("Preferences"); 

     contextMenu.getItems().addAll(item1, item2); 


     Rectangle rect = new Rectangle(100,100,150,150); 
     Button button = new Button("Button Text"); 

     // create nodes 
     Group root = new Group(); 
     root.getChildren().add(rect); 
     root.getChildren().add(button); 

     // create scrollpane 
     ScrollPane sp = new ScrollPane(root); 
     sp.setOnMousePressed(new EventHandler<MouseEvent>() { 
      @Override 
      public void handle(MouseEvent event) { 

       if (event.isSecondaryButtonDown()) { 
        contextMenu.show(sp, event.getScreenX(), event.getScreenY()); 
       } 
      } 
     }); 



     // create scene 
     Scene scene = new Scene(sp, 400, 400, Color.WHITE); 

     // add scene to primary stage 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 
} 

enter image description here

文檔說,有一個setAutoHide方法,但它並不在我的情況下工作:

指定是否彈出窗口應自動隱藏。如果彈出窗口失去焦點並且自動隱藏爲true,則彈出窗口將自動隱藏。 唯一的例外是當使用 show(javafx.scene.Node,double,double)指定owner Node時。聚焦所有者節點不會 隱藏PopupWindow。

@defaultValue假

非常感謝您!

回答

6

與父級的子元素進行交互,將獲得該父級的焦點。所以當點擊代碼中的按鈕時,上下文菜單不會隱藏。

請嘗試以下兩種方法:
1)手動管理上下文菜單的可見性,即隱藏按鈕點擊:

button.setOnAction(new EventHandler<ActionEvent>() { 
    @Override 
    public void handle(ActionEvent arg0) { 
     contextMenu.hide(); 
    } 
}); 

2)使用setContextMenu(),而不是顯示在按下鼠標右鍵菜單事件:

sp.setContextMenu(contextMenu); 
+0

setContextMenu()函數至少在您點擊任何地方時再次關閉彈出窗口。雖然我希望有一個按鈕按下並且關閉了contextpopup菜單,但是當菜單打開並且我單擊按鈕時,但它遠遠勝過我以前的版本。即始終打開的上下文菜單。我之前有過按鈕動作的機制,但由於我在滾動窗格上有一些對象,這不是一個選項。 setContextMenu是。非常感謝你! – Roland 2014-11-08 14:43:05

+0

@Uiuk Biy:你好,你能幫我解決我的問題嗎? stackoverflow.com/q/27182323/2722799 – 2014-11-28 05:41:56