user1334616
user1334616

Reputation:

Unable to get graphics context from fxml canvas

I've created a basic FXML layout with a grid and canvas side by side. I have access to the canvas object (drawArea) but after having called getGraphicsContext my gt variable is always null.

Controller Class

public class controls {
    private GraphicsContext gc;
    @FXML private Canvas drawArea;

public void start() {
    gc = drawArea.getGraphicsContext2D();
}


@FXML protected void Step(ActionEvent event) {
    //TODO code to update positions of boids.
    System.out.print("Step triggered ");


    gc.fillOval(100, 100, 10, 10);
}

}

FXML display

<SplitPane dividerPositions="0.29797979797979796" 
maxHeight="-Infinity" maxWidth="-Infinity" 
minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" 
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" 
fx:controller="controller.controls" >
  <items>

    <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
         <children>
            <GridPane hgap="15.0" prefHeight="90.0" prefWidth="175.0">
              <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
              </columnConstraints>


<rowConstraints>
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          </rowConstraints>
           <children>
              <Label text="Flock Size:" />
              <Button id="buttonStart" mnemonicParsing="false" text="Start" GridPane.columnIndex="1" GridPane.halignment="CENTER" GridPane.rowIndex="2" />
              <Button id="buttonStep" mnemonicParsing="false" onAction="#flockStep" text="Step" GridPane.halignment="CENTER" GridPane.rowIndex="1" />
              <Button mnemonicParsing="false" text="-" GridPane.columnIndex="1" GridPane.halignment="LEFT" />
              <Button mnemonicParsing="false" text="+" GridPane.columnIndex="1" GridPane.halignment="RIGHT" />
              <Button id="buttonStop" mnemonicParsing="false" text="Stop" GridPane.halignment="CENTER" GridPane.rowIndex="2" />
           </children>
        </GridPane>
     </children></AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
     <children>
        <Canvas fx:id="drawArea" height="200.0" width="200.0" />
     </children></AnchorPane>

Upvotes: 1

Views: 2799

Answers (1)

James_D
James_D

Reputation: 209428

In the controller, start() is never called. If you define an initialize() method (or just change start() to initialize()), that method will be called automatically by the FXMLLoader.

Upvotes: 2

Related Questions