简体   繁体   English

AnchorPane中的JavaFX Canvas getwidth问题

[英]JavaFX Canvas in AnchorPane getwidth issue

I am creating an Application in JavaFX with a custom Canvas class. 我正在使用自定义Canvas类在JavaFX中创建一个Application。 The custom Canvas class is nothing special, it contains no code. 自定义Canvas类没有什么特别之处,它不包含任何代码。 But when I put breakpoints in its resize function, I notice that the getWidth() is not actually updated while resizing the window. 但是当我在其resize函数中放置断点时,我注意到在调整窗口大小时实际上并没有更新getWidth()

The strange thing is, if I replace my Canvas by a different component, such as a button, then I have no issues. 奇怪的是,如果我用不同的组件替换我的Canvas,比如按钮,那么我没有问题。 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. 一些更多的测试显示,基本上从Region类继承的所有组件都可以很好地调整大小。 A region.isResizable() method returns true . region.isResizable()方法返回true A canvas on the other hand returns false when calling this method. 另一方面,画布在调用此方法时返回false

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. 但这让我更加疑惑,为什么AnchorPane无法完成这项工作。 Is it intentionally or is it a JavaFX bug ? 是有意还是JavaFX错误?

Override Canvas.isResizable() to return true. 覆盖Canvas.isResizable()以返回true。

Then override Canvas.resize() to call Canvas.setWidth() and Canvas.setHeight() 然后重写Canvas.resize()以调用Canvas.setWidth()和Canvas.setHeight()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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