I\'m using Intellij IDEA for javafx FXML development. I used the following code to simply draw an rectangle. However, it never showed up.
Main.java<
There are several questions like this on this forum, but I cannot find them with a quick search.
You should never initialize a field that is annotated @FXML
. The whole point of @FXML
is that the field is initialized during the process of loading the FXML file.
So in your class initializer, you create a Canvas
and then assign gc
to its graphics context:
@FXML public Canvas img = new Canvas(300,300);
public GraphicsContext gc = img.getGraphicsContext2D();
Then, when you load the FXML file, the FXMLLoader
creates a new Canvas
as described by the FXML, assigns that new canvas to the field img
, and places the new canvas in the scene graph (which you then display in the stage). However, gc
is still the graphics context of the original Canvas
, which you never display. So any graphics operations on gc
will never be realized.
You need
public class Controller implements Initializable {
@FXML private Canvas img ;
private GraphicsContext gc ;
@FXML private void drawCanvas(ActionEvent event) {
gc.setFill(Color.AQUA);
gc.fillRect(10,10,100,100);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
gc = img.getGraphicsContext2D();
gc.setFill(Color.BLACK);
System.out.println("color set to black");
gc.fillRect(50, 50, 100, 100);
System.out.println("draw rectangle");
}
}