JavaFX equivalent of Swing's pack()

后端 未结 1 1753
终归单人心
终归单人心 2020-12-09 16:04

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

相关标签:
1条回答
  • 2020-12-09 17:04

    Try using sizeToScene() I think this is it what you want. Let me give an example:

    JavaFX stage fitted to a button

    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.StackPane;
    import javafx.stage.Stage;
    
    public class NewFXMain extends Application {
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) {
            primaryStage.setTitle("Hello World!");
            Button btn = new Button();
            btn.setText("Say 'Hello World'");
            btn.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    System.out.println("Hello World!");
                }
            });
    
            StackPane root = new StackPane();
            root.getChildren().add(btn);
            primaryStage.setScene(new Scene(root));
            primaryStage.sizeToScene();
            primaryStage.show();
        }
    }
    
    0 讨论(0)
提交回复
热议问题