在用于调整 Canvas 大小的 javaFX 中,没有这样的方法可以做到这一点,唯一的解决方案是从 Canvas 扩展。
class ResizableCanvas extends Canvas {
public ResizableCanvas() {
// Redraw canvas when size changes.
widthProperty().addListener(evt -> draw());
heightProperty().addListener(evt -> draw());
}
private void draw() {
double width = getWidth();
double height = getHeight();
GraphicsContext gc = getGraphicsContext2D();
gc.clearRect(0, 0, width, height);
}
@Override
public boolean isResizable() {
return true;
}
}
是从 Canvas 扩展是使 Canvas 可调整大小的唯一解决方案吗?
因为此解决方案仅在我们不想使用 FXML 时才有效,如果我们在 fxml 中声明一个 Canvas ,我们如何使其可调整大小?
这是我的代码:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Main extends Application {
Controller controller;
@Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
AnchorPane root = loader.load(); // controller initialized
controller = loader.getController();
GraphicsContext gc = controller.canvas.getGraphicsContext2D();
gc.setFill(Color.AQUA);
gc.fillRect(0, 0, root.getPrefWidth(), root.getPrefHeight());
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(controller.Pane, controller.Pane.getPrefWidth(), controller.Pane.getPrefHeight()));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
最佳答案
我认为有一个指南对设置可调整大小的 Canvas 很有用:
JavaFx tip - resizable canvas
Piece of code from the guide:
/**
* Tip 1: A canvas resizing itself to the size of
* the parent pane.
*/
public class Tip1ResizableCanvas extends Application {
class ResizableCanvas extends Canvas {
public ResizableCanvas() {
// Redraw canvas when size changes.
widthProperty().addListener(evt -> draw());
heightProperty().addListener(evt -> draw());
}
private void draw() {
double width = getWidth();
double height = getHeight();
GraphicsContext gc = getGraphicsContext2D();
gc.clearRect(0, 0, width, height);
gc.setStroke(Color.RED);
gc.strokeLine(0, 0, width, height);
gc.strokeLine(0, height, width, 0);
}
@Override
public boolean isResizable() {
return true;
}
@Override
public double prefWidth(double height) {
return getWidth();
}
@Override
public double prefHeight(double width) {
return getHeight();
}
}
关于javafx - 如何在javaFX中使 Canvas 可调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24533556/