JavaFX相当于Swing的pack()

时间:2012-12-31 09:26:44

标签: java swing javafx-2

我想调整窗口大小以适应窗口的内容。在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 个答案:

答案 0 :(得分:18)

尝试使用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();
    }
}