我正在处理我在 JavaFX 中构建的关卡编辑器的 GUI,我希望能够将 Canvas 对象的大小调整为新的拆分 Pane 尺寸。似乎我尝试过的一切都失败了。这包括将 Pane 对象传入并直接使用其宽度,使用窗口大小监听器并将宽度和高度属性绑定(bind)到拆分 Pane 的属性。有任何想法吗?这是调整大小之前的样子:
调整大小后:
有人有什么想法吗?该类的代码非常广泛,但调整大小的代码将包含在此处:
public Canvas canvas;
public String tabTitle;
public VBox layout;
public GraphicsContext g;
public Core core;
public CanvasTab(Core core, String tabTitle){
this.core = core;
this.canvas = new Canvas(core.scene.getWidth() - 70, core.scene.getHeight() - 70);
layout = VBoxBuilder.create().spacing(0).padding(new Insets(10, 10, 10, 10)).children(canvas).build();
this.g = canvas.getGraphicsContext2D();
g.setFill(Color.BLACK);
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
HBox.setHgrow(layout, Priority.ALWAYS);
this.setContent(layout);
this.setText(tabTitle);
canvas.widthProperty().bind(layout.widthProperty().subtract(20));
canvas.heightProperty().bind(layout.heightProperty().subtract(20));
}
public CanvasTab(Canvas canvas){
this.canvas = canvas;
}
最佳答案
正如 James_D 所指出的,您需要在调整大小时重新绘制 Canvas 的内容。这可以通过向 Canvas 的宽度和高度属性添加一个监听器来完成,如下所示:
InvalidationListener listener = new InvalidationListener(){
@Override
public void invalidated(Observable o) {
redraw();
}
});
canvas.widthProperty().addListener(listener);
canvas.heightProperty().addListener(listener);
或者在 Java 8 中使用函数式接口(interface):
canvas.widthProperty().addListener(observable -> redraw());
canvas.heightProperty().addListener(observable -> redraw());
其中 redraw()
是您自己的方法,在您的示例中看起来像这样(绘制一个黑色矩形:
private void redraw() {
g.setFill(Color.BLACK);
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
关于JavaFX - 调整屏幕大小时调整 Canvas 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449932/