JavaFX - 调整屏幕大小时调整画布大小

Mar*_*utt 7 java resize javafx canvas

我正在使用我在JavaFX中构建的关卡编辑器的GUI,我希望能够将画布对象的大小调整为新的拆分窗格尺寸.看来我试过的一切都失败了.这包括直接传递窗格对象并使用它的宽度,使用窗口大小侦听器并将width和height属性绑定到拆分窗格的属性.有任何想法吗.这是调整大小之前的松散之处:

在此输入图像描述

调整大小后:

在此输入图像描述

有没有人有任何想法.该类的代码非常广泛,但将包含调整大小的代码.

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;
}
Run Code Online (Sandbox Code Playgroud)

sch*_*erd 12

正如James_D指出的那样,你需要在调整大小时重绘画布的内容.这可以通过向画布的width和height属性添加一个侦听器来完成,如下所示:

InvalidationListener listener = new InvalidationListener(){
    @Override
    public void invalidated(Observable o) {
        redraw();       
    }           
});
canvas.widthProperty().addListener(listener);
canvas.heightProperty().addListener(listener);
Run Code Online (Sandbox Code Playgroud)

或者在Java 8中使用功能接口:

canvas.widthProperty().addListener(observable -> redraw());
canvas.heightProperty().addListener(observable -> redraw());
Run Code Online (Sandbox Code Playgroud)

redraw()您自己的方法在哪里,对于您的示例看起来像这样(绘制一个黑色矩形:

private void redraw() {
    g.setFill(Color.BLACK);
    g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
Run Code Online (Sandbox Code Playgroud)

  • 根据我有限的经验,您必须获取场景的 widthProperty 和 heightProperty,而不是画布的:https://blog.idrsolutions.com/2012/11/adding-a-window-resize-listener-to-javafx-scene/ (2认同)

小智 6

要使JavaFx画布可调整大小,需要完成的任务是覆盖min/pref/max方法.使其可调整大小并实现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();
}
Run Code Online (Sandbox Code Playgroud)

请注意,resize方法不能简单地调用Node.resize(width,height),因为标准实现是有效的空.