我无法将此代码转换为场景生成器...
问题出在事件处理程序中。...
我没有得到如何在Java中使用ConfirmCloseEventHandler事件处理程序 FX场景构建器...
提前谢谢。
主要我不能在fxml控制器中使用这些事件处理程序...
public class Javafxpopupmessage extends Application {
private Stage mainStage;
@Override
public void start(Stage stage) throws Exception {
this.mainStage = stage;
stage.setOnCloseRequest(confirmCloseEventHandler);
Button closeButton = new Button("Close Application");
closeButton.setOnAction(event ->
stage.fireEvent(
new WindowEvent(
stage,
WindowEvent.WINDOW_CLOSE_REQUEST
)
)
);
StackPane layout = new StackPane(closeButton);
layout.setPadding(new Insets(100));
stage.setScene(new Scene(layout));
stage.show();
}
private EventHandler<WindowEvent> confirmCloseEventHandler = event -> {
Alert closeConfirmation = new Alert(
Alert.AlertType.CONFIRMATION,
"Are you sure you want to exit?"
);
Button exitButton = (Button)
closeConfirmation.getDialogPane().lookupButton(
ButtonType.OK
);
exitButton.setText("Exit");
closeConfirmation.setHeaderText("Confirm Exit");
closeConfirmation.initModality(Modality.APPLICATION_MODAL);
closeConfirmation.initOwner(mainStage);
// normally, you would just use the default alert positioning,
// but for this simple sample the main stage is small,
// so explicitly position the alert so that the main window can still be
seen.
// closeConfirmation.setX(mainStage.getX());
//closeConfirmation.setY(mainStage.getY() + mainStage.getHeight());
Optional<ButtonType> closeResponse = closeConfirmation.showAndWait();
if (!ButtonType.OK.equals(closeResponse.get())) {
event.consume();
}
};
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:0)
通过fxml为主要阶段注册一些处理程序只能用不好的技巧来完成,因为FXMLLoader
只能访问自己创建的对象。
您可以在场景中某个节点的Node.scene
属性中添加一个侦听器,并在设置场景后立即将其添加到该场景的window
属性中,并在其进入后立即访问窗口分配,这对于在start
方法中使用更简单的代码即可完成的事情来说非常复杂。
除了这种黑客之外,您将无法在start
方法中注册该事件处理程序(或将Stage
传递给控制器,导致代码比发布的代码复杂)。
关于关闭按钮onAction
事件:您可以将控制器的方法用作处理程序:
<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="mypackage.MyController">
<children>
<Button text="Close Application" onAction="#close"/>
</children>
<padding>
<Insets topRightBottomLeft="100"/>
</padding>
</StackPane>
package mypackage;
...
public class MyController {
@FXML
private void close(ActionEvent event) {
Node source = (Node) event.getSource();
Window window = source.getScene().getWindow();
window.fireEvent(new WindowEvent(
window,
WindowEvent.WINDOW_CLOSE_REQUEST));
}
}