我是JavaFX的新手,我遇到了绑定问题。
我正在编写一个游戏,我在GridPane
的单元格中的窗格之间绘制线条。我可以使用下面的代码绘制线条,但是当我调整窗口大小时,我希望将线条坐标缩放为窗格变大。
Pane
和GridPane
已根据需要调整大小,我设法将线条的宽度绑定到场景的大小(cellSize是场景宽度/高度的绑定)
Pane lastPane = panes[lastC][lastR];
Pane curPane = panes[c][r];
Bounds boundsInSceneLast = lastPane.localToScene(lastPane.getBoundsInLocal());
Bounds boundsInSceneCur = curPane.localToScene(curPane.getBoundsInLocal());
double lastX = (boundsInSceneLast.getMinX() + boundsInSceneLast.getMaxX())/2;
double lastY = (boundsInSceneLast.getMinY() + boundsInSceneLast.getMaxY())/2;
double x = (boundsInSceneCur.getMinX() + boundsInSceneCur.getMaxX())/2;
double y= (boundsInSceneCur.getMinY() + boundsInSceneCur.getMaxY())/2;
Line line = new Line(lastX, lastY, x, y);
line.setStroke(Color.web(couleurs.get(symbole)));
line.strokeWidthProperty().bind(cellSize.divide(10));
line.setStrokeLineCap(StrokeLineCap.BUTT);
anchor.getChildren().add(line);
lines.get(symbole).add(line);
anchor
是AnchorPane
,它是Scene
的根,lines
是HashMap
跟踪线条,但那些不应该'与我的问题有关。
我确信它可以很简单地完成,但我已经非常深入地搜索了网页,而我所能理解和尝试的并没有完成任务,所以我正在寻求你的帮助。
提前致谢!! :)
答案 0 :(得分:1)
在场景中监听Node
的边界是有问题的,因为场景边界没有属性,并且场景根节点的路径上的每个Parent
都可以应用变换需要您调整线端的位置。这将要求您向Pane
的后代添加侦听器。
将这些行作为非托管节点成为GridPane
本身的一部分会更简单。这允许您使用GridPane
:
final Pane lastPane = panes[lastC][lastR];
final Pane curPane = panes[c][r];
final Line line = new Line();
line.setStroke(Color.web(couleurs.get(symbole)));
line.strokeWidthProperty().bind(cellSize.divide(10));
line.setStrokeLineCap(StrokeLineCap.BUTT);
InvalidationListener listener = o -> {
Bounds boundsInSceneLast = lastPane.getBoundsInParent();
Bounds boundsInSceneCur = curPane.getBoundsInParent();
double lastX = (boundsInSceneLast.getMinX() + boundsInSceneLast.getMaxX())/2;
double lastY = (boundsInSceneLast.getMinY() + boundsInSceneLast.getMaxY())/2;
double x = (boundsInSceneCur.getMinX() + boundsInSceneCur.getMaxX())/2;
double y = (boundsInSceneCur.getMinY() + boundsInSceneCur.getMaxY())/2;
line.setStartX(lastX);
line.setStartY(lastY);
line.setEndX(x);
line.setEndY(y);
};
// listen to location & size changes of panes in the GridPane
lastPane.boundsInParentProperty().addListener(listener);
curPane.boundsInParentProperty().addListener(listener);
// initial refresh
listener.invalidated(null);
// add line to GridPane without considering it for layout
line.setManaged(false);
gridPane.getChildren().add(line);
lines.get(symbole).add(line);