JavaFX – 调整屏幕大小时调整canvas大小
我正在使用我在JavaFX中构建的关卡编辑器的GUI,我希望能够将canvas对象的大小调整为新的拆分窗格尺寸。 似乎所有尝试的东西都失败了。 这包括直接传递窗格对象并使用它的宽度,使用窗口大小侦听器并将width和height属性绑定到拆分窗格的属性。 有任何想法吗。 这是resize之前的松散之处:
resize后:
有没有人有任何想法。 该类的代码非常广泛,但将包含resize的代码。
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指出的那样,你需要在resize时重绘canvas的内容。 这可以通过向canvas的width和height属性添加一个侦听器来完成,如下所示:
InvalidationListener listener = new InvalidationListener(){ @Override public void invalidated(Observable o) { redraw(); } }); canvas.widthProperty().addListener(listener); canvas.heightProperty().addListener(listener);
或者在Java 8中使用function接口:
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()); }
要使JavaFxcanvas可resize,需要完成的任务是覆盖min / pref / max方法。 使其可resize并实现resize方法。
使用此方法,不需要宽度/高度侦听器来触发重绘。 也不再需要将宽度和高度的大小绑定到容器。
public class ResizableCanvas extends Canvas { @Override public double minHeight(double width) { return 64; } @Override public double maxHeight(double width) { return 1000; } @Override public double prefHeight(double width) { return minHeight(width); } @Override public double minWidth(double height) { return 0; } @Override public double maxWidth(double height) { return 10000; } @Override public boolean isResizable() { return true; } @Override public void resize(double width, double height) { super.setWidth(width); super.setHeight(height); paint(); }
请注意,resize方法不能简单地调用Node.resize(width,height),因为标准实现是有效的。