有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Javafx中的java当打开一个窗口时,如何设置它以使用户无法再次打开同一个窗口?

我试了很多,但就是找不到任何解决办法。此时,打开的窗口(弹出窗口)始终位于顶部,但用户仍可以访问主窗口。应该是这样的,但不可能再次打开同一个弹出窗口。

    Stage stage = new Stage();
    stage.setTitle(panelTitle);     
    stage.setScene(new Scene(root));
    stage.initModality(Modality.WINDOW_MODAL); 
    stage.setAlwaysOnTop(true);
    stage.showAndWait();

提前谢谢!


共 (2) 个答案

  1. # 1 楼答案

    每次创建一个新的解决方案的另一种方法是创建一个,然后设置并显示

    public class Stack extends Application {
    
        private final Stage popup = new Stage();
    
        @Override
        public void start(Stage stage) throws Exception {
    
            BorderPane root = new BorderPane();
            root.setPrefWidth(400);
            root.setPrefHeight(200);
    
            Button button = new Button("ClickMePopup");
    
            root.setCenter(button);
    
            button.setOnAction(
                    event -> {
                        if (!popup.isShowing()) {
                            // you dont set modality because after the stage is set to visible second time it will throw an exception.
                            // Again depends on what you need.
                            // popup.initModality(Modality.WINDOW_MODAL);
    
                            // this focuses the popup and main window is not clickable
                            // popup.initOwner(stage);
    
                            VBox dialogVbox = new VBox(20);
                            dialogVbox.getChildren().add(new Text("Some Dialog"));
                            Scene dialogScene = new Scene(dialogVbox, 300, 200);
                            popup.setScene(dialogScene);
    
                            // you can actually put all above into the method called initPopup() or whatever, do it once, and just show it here or just bind the property to the button.
    
                            popup.show();
                        }
                    });
    
            Scene scene = new Scene(root);
    
            stage.setTitle("Stack");
            stage.setScene(scene);
            stage.show();
    
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    
    }
    

    或者在单击时禁用按钮,但是如果您的弹出窗口不是由按钮驱动的,或者可以从其他位置打开,那么我认为第一个想法会更好一些。取决于你需要什么

    或者创建自己的类并将其Springify

  2. # 2 楼答案

    正如LazerBanana所说,我会禁用打开窗口的按钮,当你关闭它时,我会启用它

    Stage stage = new Stage();
    button.setDisable(true);
    stage.setTitle(panelTitle);     
    stage.setScene(new Scene(root));
    stage.initModality(Modality.WINDOW_MODAL); 
    stage.setAlwaysOnTop(true);
    stage.showAndWait();
    // your logic here
    button.setDisable(false);