简体   繁体   中英

JavaFX Canvas in AnchorPane getwidth issue

I am creating an Application in JavaFX with a custom Canvas class. The custom Canvas class is nothing special, it contains no code. But when I put breakpoints in its resize function, I notice that the getWidth() is not actually updated while resizing the window.

The strange thing is, if I replace my Canvas by a different component, such as a button, then I have no issues. The width is updated correctly.

public class MyApp extends Application
{

  @Override
  public void start(Stage primaryStage) throws Exception
  {
    primaryStage.setTitle("Test");

    CustomCanvas canvas = new CustomCanvas();

    AnchorPane.setTopAnchor(canvas, 0d);
    AnchorPane.setLeftAnchor(canvas, 0d);
    AnchorPane.setBottomAnchor(canvas, 0d);
    AnchorPane.setRightAnchor(canvas, 0d);

    AnchorPane root = new AnchorPane();
    root.getChildren().add(canvas);
    root.setPrefWidth(500);
    root.setPrefHeight(500);

    primaryStage.setScene(new Scene(root,500,500));
    primaryStage.show();
  }

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

Some more testing revealed that basically all components that inherit from the Region class resize fine. A region.isResizable() method returns true . A canvas on the other hand returns false when calling this method.

I can of course use a workaround by binding the properties. Works fine.

CustomCanvas canvas = new CustomCanvas();
canvas.widthProperty().bind(primaryStage.widthProperty());
canvas.heightProperty().bind(primaryStage.heightProperty());

But that makes me wonder even more, why the AnchorPane cannot do the job. Is it intentionally or is it a JavaFX bug ?

Override Canvas.isResizable() to return true.

Then override Canvas.resize() to call Canvas.setWidth() and Canvas.setHeight()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM