JavaFx调整窗口大小并保留纵横比

时间:2017-06-09 06:12:19

标签: java javafx fxml

目前我正在开发一个JavaFX应用程序,我想调整Window的大小。 每次我调整窗口大小时,它都会回到初始大小。

Globals.java

public class Globals {
  public static Stage primaryStage;
  public static int drawFactor;
  public static int initWidth = 800;
  public static int initHeight = 600;
}

Main.java

public class Main extends Application {

  public static void main(String[] args) {
      launch(args);
  }

  @Override
  public void start(Stage primaryStage) throws Exception {
          Parent root = FXMLLoader.load(getClass().getResource("/fxml/MainWindow.fxml"));
          Scene rootScene = new Scene(root, Globals.initWidth, Globals.initHeight);
          primaryStage.setScene(rootScene);
          primaryStage.setTitle("JavaFX Application");
          primaryStage.show();
          Globals.primaryStage = primaryStage;
  } 
}

Controller.java

public class Controller {
@FXML
private StackPane pane;
@FXML
private Canvas canvas;

  /**
  * Method is called at start of the app, because it is in the FXML controller
  */
  public void initialize() {
      canvas.widthProperty().bind(pane.widthProperty());
      canvas.heightProperty().bind(pane.heightProperty());
      canvas.widthProperty().addListener(new ChangeListener<Number>() {
        @Override
          public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
              Globals.drawFactor = (double) newValue / Globals.initWidth;
              pane.resize((double) newvalue, Globals.initHeight * Globals.drawFactor);
              if(Globals.primaryStage != null) {
                Globals.primaryStage.getScene().getWindow().setHeight(Globals.initHeight * Globals.drawFactor);
              }
          }
      });
  }
}

MainWindow.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.layout.StackPane?>
<StackPane fx:id="pane" xmlns="http://javafx.com/javafx/8.0.60"
       xmlns:fx="http://javafx.com/fxml/1"
       fx:controller="Controller">
    <Canvas fx:id="canvas"/>
</StackPane>

如果我调整窗口大小并且CanvasWidth Changelistener触发器,则窗口大小会更改,但最终WindowHeight会快速恢复到初始值(在此示例中为600)。宽度接受新值。

有没有办法解决此问题或调整窗口大小并保持纵横比?

0 个答案:

没有答案