JavaFX技巧1:可调整大小的Canvas
在使用FlexGanttFX时,我不得不处理很多JavaFX Canvas节点。 我正在使用它在时间轴上呈现活动。 甘特图中的每一行都是一个Canvas节点。 用户可以选择单独调整每行的大小。 因此,我不得不找出调整画布大小的最佳方法,这种现成的方法无法调整大小。 下面的清单显示了如何实现此目的。
所需的主要步骤是:
- 创建Canvas的子类。
- 重写isResizable()方法并返回true。
- 重写prefWidth()和prefHeight()方法。 返回Canvas.getWidth()和Canvas.getHeight()的值。
- 将侦听器添加到“ 画布”的width和height属性中,以便在画布大小更改时触发重绘。
- 将“画布”的width和height属性绑定到父窗格的width和height属性。
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * 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(); } } @Override public void start(Stage stage) throws Exception { ResizableCanvas canvas = new ResizableCanvas(); StackPane stackPane = new StackPane(); stackPane.getChildren().add(canvas); // Bind canvas size to stack pane size. canvas.widthProperty().bind( stackPane.widthProperty()); canvas.heightProperty().bind( stackPane.heightProperty()); stage.setScene(new Scene(stackPane)); stage.setTitle("Tip 1: Resizable Canvas"); stage.show(); } public static void main(String[] args) { launch(args); } }
翻译自: https://www.javacodegeeks.com/2014/04/javafx-tip-1-resizable-canvas.html