首页 > 解决方案 > 在 anchorPane 中调整图形元素(网格窗格)的大小

问题描述

我的任务是以全屏模式创建可调整大小的图形。当用户更改默认全屏的程序窗口时,图形必须可调整大小(图形的组件和线条会改变它们的大小)。我通过以下方式实现图形AnchorPane:元素(即GridPanes)保持在定义的坐标中。然后我在 method 的帮助下画线getBoundsInParent()。这是图的场景:

图片

一切都很好,但问题是我无法调整图表的大小。所有组件都保持其大小;variables prefSize, minSize,maxSize不要调整大小。我尝试使用参数AnchorPane.setTopAnchor等,但它们不会调整大小,只会移动GridPane组件。我也尝试使用GridPane作为布局而不是AnchorPane. 但是我与方法绑定的行在component.getBoundsInParent()随机位置飞走(我知道该getBoundsInParent()方法返回与 其他坐标GridPane)。

我的项目位于没有互联网的工作计算机上,我无法显示它。我认为绑定图表之间的线条的方式对于在代码块中显示很有用,因为它是当组件处于 GridPane 布局时移出线条的原因:

line.startXProperty().bind(source.layoutXProperty().add(source.getBoundsInParent().getWidth() / 2.0));    
line.startYProperty().bind(source.layoutYProperty().add(source.getBoundsInParent().getHeight() / 2.0));
line.endXProperty().bind(target.layoutXProperty().add(target.getBoundsInParent().getWidth() / 2.0));
line.endYProperty().bind(target.layoutYProperty().add(target.getBoundsInParent().getHeight() / 2.0));

用我创建的元素和与这些元素连接的线来调整图形大小的方法是什么。可能是AnchorPaneor的属性GridPane?或者线的起点和终点的一些绑定?

标签: javajavafx

解决方案


绑定需要基于属性或其他 ObservableValue 实现,因此可以正确跟踪对其值的更改。像这样的直接方法调用source.getBoundsInParent().getWidth() / 2.0只评估一次,即代码创建绑定的那一刻,因此永远不会看到对宽度的更改。

line.startXProperty().bind(
    source.layoutXProperty().add(
        source.widthProperty().divide(2)));
line.startYProperty().bind(
    source.layoutYProperty().add(
        source.heightProperty().divide(2)));

如果source并且target不是 Regions 并因此没有width属性,则可以使用Bindings创建其边界的动态绑定:

DoubleBinding width = Bindings.createDoubleBinding(
    () -> source.getLayoutBounds().getWidth(), 
    source.layoutBoundsProperty());

line.startXProperty().bind(
    source.layoutXProperty().add(
        Bindings.createDoubleBinding(width.divide(2)));

DoubleBinding height = Bindings.createDoubleBinding(
    () -> source.getLayoutBounds().getHeight(), 
    source.layoutBoundsProperty());

line.startYProperty().bind(
    source.layoutYProperty().add(
        Bindings.createDoubleBinding(height.divide(2)));

推荐阅读