I want to resize a window to fit the contents of the window. In Swing there is the pack()
method. Is there a similar method to do this in JavaFX?
What I am trying to do is to create a confirmation dialog. When I create the dialog, it is wider than the contents, so I was asking myself if I need something like the pack method.
Here is a screenshot of what is happening:
And here is my code:
mainClass.getPrimaryStage().setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(final WindowEvent e) {
e.consume();
final Stage dialog = new Stage();
dialog.setTitle("Confirm Before Exit");
dialog.setResizable(false);
dialog.initOwner(mainClass.getPrimaryStage());
dialog.initModality(Modality.APPLICATION_MODAL);
FlowPane buttons = new FlowPane(10,10);
buttons.setAlignment(Pos.CENTER);
Button yes = new Button("Yes");
Button no = new Button("No");
buttons.getChildren().addAll(yes, no);
VBox box = new VBox();
box.setAlignment(Pos.CENTER);
box.setSpacing(10);
box.getChildren().addAll(new Label("Do you really want to exit?"), buttons);
yes.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
Platform.exit();
}
});
no.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
dialog.close();
}
});
Scene s = new Scene(box);
dialog.setScene(s);
dialog.show();
}
});
I hope they implement something like JOptionPane
in JavaFX soon! This is not something that I should be doing, it is so basic...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…