带有Canvas的嵌套BorderPane只会增长,永不缩小

时间:2018-04-14 00:30:47

标签: javafx-8 borderpane

我有一个包含Canvas的BorderPane,其中包含Canvas'绑定到BorderPane属性的高度和宽度属性。 BorderPane又是场景的根源。

一切正常。如果我调整窗口大小,BorderPane的大小会更改以匹配场景的大小,并且Canvas会更改以匹配BorderPane的大小。

但是,如果我引入另一个BorderPane,它将停止工作:内部BorderPane和Canvas将随着Scene和外部BorderPane的增长而增长,但是当我缩小窗口时,它们不会缩小。

  Working:            Not working:

 ┌──────────────┐    ┌────────────────┐
 │    Scene     │    │     Scene      │
 │┌────────────┐│    │┌──────────────┐│
 ││ BorderPane ││    ││  BorderPane  ││
 ││┌──────────┐││    ││┌────────────┐││
 │││  Canvas  │││    │││ BorderPane │││
 ││└──────────┘││    │││┌──────────┐│││
 │└────────────┘│    ││││  Canvas  ││││
 └──────────────┘    │││└──────────┘│││
                     ││└────────────┘││
                     │└──────────────┘│
                     └────────────────┘

有效的代码:

BorderPane parent = new BorderPane();
Canvas canvas = new Canvas();
canvas.widthProperty().bind(parent.widthProperty());
canvas.heightProperty().bind(parent.heightProperty());
parent.setCenter(canvas);
Scene scene = new Scene(parent);
stage.setScene(scene);
stage.show();

不起作用的代码:

BorderPane inner = new BorderPane();

Canvas canvas = new Canvas();
canvas.widthProperty().bind(inner.widthProperty());
canvas.heightProperty().bind(inner.heightProperty());
inner.setCenter(canvas);

BorderPane outer = new BorderPane();
outer.setCenter(inner);

Scene scene = new Scene(outer);
stage.setScene(scene);
stage.show();

我添加了一些日志记录来确认问题:

# scene, outer pane, inner pane, and canvas growing
outer width: 1364.0 -> 1374.0
scene width: 1364.0 -> 1374.0
outer height: 339.0 -> 342.0
scene height: 339.0 -> 342.0
canvas width: 1364.0 -> 1374.0
inner width: 1364.0 -> 1374.0
canvas height: 339.0 -> 342.0
inner height: 339.0 -> 342.0
# scene and outer pane shrinking, canvas and inner not
outer width: 1374.0 -> 1327.0
scene width: 1374.0 -> 1327.0
outer height: 342.0 -> 330.0
scene height: 342.0 -> 330.0
outer width: 1327.0 -> 1290.0
scene width: 1327.0 -> 1290.0
outer height: 330.0 -> 326.0
scene height: 330.0 -> 326.0

显然在这个玩具示例中我可以删除中间BorderPane,但是如果我想制作一个可重复使用,可调整大小的组件包装Canvas呢?如何确保它始终与父母一起调整大小?无论如何,与嵌套BorderPanes的交易是什么?

1 个答案:

答案 0 :(得分:2)

Canvas是一个不可调整大小的节点。这意味着它的大小是其父级min大小的下限。

如果使用BorderPane作为场景根,则调整窗口大小会强制调整场景大小并调整场景大小,强制调整场景根大小以适合窗口。出于这个原因,Canvas的父级缩小到它min以下,Canvas缩小了。

如果缩小BorderPane以下min尺寸,则不会强制其可调整大小的儿童调整到min尺寸以下,但会设置其尺寸改为min大小。这样,BorderPane中包含的BorderPane永远不会被强制缩小到Canvas以下,而Canvas永远不会缩小。

您可以通过将managed的{​​{1}}属性设置为Canvas来解决此问题,从而导致在计算false尺寸时未考虑Canvas 。 (请注意,根本不考虑非托管子项的布局。因此,您应该将min作为唯一的子项包装在Canvas中,以防止对兄弟姐妹产生不良影响。)

Pane
相关问题