在JavaFX中显示警告对话框时,防止关闭上下文菜单

时间:2016-02-19 21:41:29

标签: javafx dialog contextmenu alert alertdialog

我有一个上下文菜单,其中包含带有一些控件的CustomMenuItem。单击按钮时,将显示一个对话框,并且上下文菜单会自动隐藏。这是问题所在:我想在对话框显示时阻止关闭上下文菜单。我该如何解决这个问题?

我已经跟踪完成了这个事件。对话框打开时,将触发FocusUngrabEvent.FOCUS_UNGRAB事件,该事件在PopupWindow中处理。我已经尝试将EventFilter和EventHandler添加到FocusUngrabEvent.FOCUS_UNGRAB的上下文菜单中并使用该事件,但这没有用。

这里有一个SSCCE证明了这个问题:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class PimaryStage extends Application {

    @Override
    public void start(Stage primaryStage) {
        // The button which shows the dialog.
        Button button = new Button("Some Button");
        button.setOnAction((event)-> {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("Warning");
            alert.setHeaderText(null);
            alert.setContentText("Some Text");

            alert.show();
        });

        // Custom menu item which contains the button.
        CustomMenuItem menuItem = new CustomMenuItem(button);
        menuItem.setHideOnClick(false);

        // Context menu.
        ContextMenu menu = new ContextMenu();
        menu.getItems().add(menuItem);

        // Label.
        Label label = new Label("Click here to open the context menu.");
        label.setContextMenu(menu);

        // Set the scene and show the stage.
        Scene scene  = new Scene(label, 300, 250);
        primaryStage.setScene(scene);

        primaryStage.show();
    }

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这对我有用:

@FXML
public void autoShow() {
    contextmenu.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            e.consume();
        }
    });


}

将上述方法放在控制器类中,然后从控制器类的initialize方法中调用它:

@Override 
public void initialize(URL location, ResourceBundle resources) {

    autoShow();

}
相关问题