JavaFX 相当于 Swing 的 pack()

2022-09-01 23:36:10

我想调整窗口大小以适合窗口的内容。在 Swing 中,有 pack() 方法。在JavaFX中是否有类似的方法来执行此操作?

我正在尝试做的是创建一个确认对话框。当我创建对话框时,它比内容更宽,所以我问自己是否需要类似pack方法的东西。

以下是正在发生的事情的屏幕截图:enter image description here

这是我的代码:

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();
    }
});

我希望他们能很快在JavaFX中实现类似JOptionPane的东西!这不是我应该做的事情,它是如此基本...


答案 1

尝试使用我认为这就是你想要的。让我举个例子:sizeToScene()

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();
    }
}

答案 2

推荐