用户调整大小后,JavaFx会保持窗口大小

时间:2014-12-12 22:29:22

标签: java javafx javafx-2 fxml scene

我目前使用以下代码在场景之间切换。我想在窗口之间切换并保持窗口大小(因此当用户通过调整窗口大小来手动更改窗口大小时,即使在场景更改后它也会保持所选的大小。)

Scene scene = new Scene(pane); // new Scene(pane, userChosenWidth??, userChosenHeight??); stage.setScene(scene); stage.sizeToScene();

有谁知道如何做到这一点?

2 个答案:

答案 0 :(得分:0)

只需在当前getWidth()上拨打getHeight()Scene即可。如果您没有对当前场景的引用,则可以使用stage.getScene()

答案 1 :(得分:0)

我创建了这个类:

public class AppSize {

    private static final String HEIGHT = "Height";
    private static final String WIDTH = "Width";
    private static final String Y = "Y";
    private static final String X = "X";

    private final static Preferences prefs =  Preferences.userNodeForPackage(AppSize.class);

    public static void setSize(Stage stage) {

    Optional.ofNullable(prefs.getDouble(X, -1)).filter(x->x>=0).ifPresent(stage::setX);
    Optional.ofNullable(prefs.getDouble(Y, -1)).filter(y->y>=0).ifPresent(stage::setY);
    Optional.ofNullable(prefs.getDouble(WIDTH, -1)).filter(width->width>=0).ifPresent(stage::setWidth);
    Optional.ofNullable(prefs.getDouble(HEIGHT, -1)).filter(height->height>=0).ifPresent(stage::setHeight);

    stage.setOnCloseRequest(
            e->{

                if(stage.isFullScreen()) {
                    return;
                }

                prefs.putDouble(X, stage.getX());
                prefs.putDouble(Y, stage.getY());
                prefs.putDouble(WIDTH, stage.getWidth());
                prefs.putDouble(HEIGHT, stage.getHeight());
            });
    }
}

它的用途:

 public void start(Stage stage) throws Exception {
    //...
    AppSize.setSize(stage);
    stage.show();
}