Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

events - JavaFX - Why is my FileChooser giving me access to the origin Stage?

When i click on the button, a FileChooser is opened. However, i can for example close the Original Stage while the FileChooser is still opened, or i still can click and switch the actual window. Check the code below

My questions are :
1- How can i make the FileChooser Closes when i close the main window ?
2- How can i make the main window not clickable when the FileChooser is opened ?

package application;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;

public class Main extends Application {

    @Override public void start(Stage stage) {

        stage.setTitle("Main Stage");
        stage.setWidth(500);
        stage.setHeight(500);
        stage.show();
        Button button = new Button();
        AnchorPane ap = new AnchorPane();
        Scene scene = new Scene(ap);
        ap.getChildren().addAll(button);
        stage.setScene(scene);

        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent e) {
                FileChooser fileChooser = new FileChooser();
                Stage stage2=new Stage();
                stage2.initOwner(stage);
                stage2.initModality(Modality.WINDOW_MODAL);
                fileChooser.showOpenDialog(stage2);  
           }
       });  
    }

    public static void main(String[] args) {
        launch(args);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the JavaDocs

If the owner window for the file dialog is set, input to all windows in the dialog's owner chain is blocked while the file dialog is being shown.

However, you are setting the owner window to a window that is not on the screen, so I think there is no "owner chain" in that case, and the file chooser is effectively not modal.

Why not just do

    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent e) {
            FileChooser fileChooser = new FileChooser();
            fileChooser.showOpenDialog(stage); 
       }
   });

so that you make the owner window of the file chooser the actual window?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...