PawelW PawelW - 5 days ago 5
Java Question

JavaFX I can't draw anything on canvas created in Scene Builder

I created scene in SceneBuilder which included canvas object. Now I'm trying to draw anything on canvas, but nothing appear. Maybe someone could tell me what I'm doing wrong. Thanks in advice.

Here is declaration of canvas object:

public class ApplicationControler implements Initializable {

@FXML
public Canvas artHorizon;


And the method which should draw something on it:

public void drawOval(){
artHorizon = new Canvas(400, 400);
GraphicsContext gc = artHorizon.getGraphicsContext2D();

gc.setFill(Color.DARKRED);
gc.fillOval(110, 30, 50, 50);
}


And the Main class:

public class Main extends Application {

@Override
public void start(Stage stage) throws Exception {

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/application/MainPane.fxml"));
Parent parent = fxmlLoader.load();
Scene scene = new Scene(parent);


stage.setScene(scene);
stage.setTitle("Login Page");
stage.show();

ApplicationControler controller = fxmlLoader.getController();
controller.drawOval();

}

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


}

Answer

I think you should remove:

artHorizon = new Canvas(400, 400);

See if you can do something like this:

artHorizon.setHeight(400);
artHorizon.setWidth(400);
Comments