如何在FXMLDocumentController中与画布交互

时间:2019-06-23 01:18:24

标签: javafx

我想在按下按钮后在画布上绘制像素(因此在FXMLDocumentController的handleButtonAction函数中)

public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;
    private Canvas canvas;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        //I'd like to perform the interaction with the Canvas here
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    

}

但是在我所看到的所有地方,我都只看到在启动功能中更改了画布的示例,

public class BasicOpsTest extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Drawing Operations Test");
        Group root = new Group();
        Canvas canvas = new Canvas(300, 250);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        drawShapes(gc);
        root.getChildren().add(canvas);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    private void drawShapes(GraphicsContext gc) {
        gc.setFill(Color.GREEN);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(5);
        gc.strokeLine(40, 10, 10, 40);
    }
}

有办法吗?

1 个答案:

答案 0 :(得分:2)

您为什么不尝试一下呢?您可以随时操作画布。这既不绑定到start方法,也不绑定到initialize方法。但是我想您必须在画布元素上添加一个额外的@FXML批注才能使它正常工作。