我有一个充当弹出窗口的阶段,如果用户在该阶段外部点击,我想关闭舞台,如何实现这一点,我作为弹出窗口的代码如下:
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("colorchange.fxml"));
Scene sce = new Scene(root,400,400);
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(color.getScene().getWindow());
stage.setScene(sce);
stage.showAndWait();
答案 0 :(得分:1)
使用stage.focusedProperty()
注册听众,如果焦点属性更改为stage.hide()
,则调用false
。
SSCCE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class CloseWindowOnClickOutside extends Application {
@Override
public void start(Stage primaryStage) {
Button showPopup = new Button("Show popup");
showPopup.setOnAction(e -> {
Stage popup = new Stage();
Scene scene = new Scene(new Label("Popup"), 120, 40);
popup.setScene(scene);
popup.initModality(Modality.APPLICATION_MODAL);
popup.initOwner(primaryStage);
popup.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
if (! isNowFocused) {
popup.hide();
}
});
popup.show();
});
StackPane root = new StackPane(showPopup);
Scene scene = new Scene(root, 350, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}