Not able to add Canvas in main.java (JavaFX)

536 views Asked by At

I am working with JavaFX and I am trying to add a canvas to the root. Below is the code:

public void start(Stage stage) throws Exception {
    //Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
    //Scene scene = new Scene(root);
    stage.setTitle("Hello, World!");
    Group root=new Group();
    Scene scene=new Scene(root,300,300,Color.BLACK);
    stage.setScene(scene);
    final Canvas canvas = new Canvas(100,100);
    root.getChildren().add( canvas );
    //GraphicsContext gc = canvas.getGraphicsContext2D();
    //root.getChildren().add( canvas );
    stage.show();
}

I am getting an error : No suitable constructor found for Canvas(int, int) (actual and formal argument list differ in length). According to the official website, this is exactly how we add a canvas, yet this error. I could not find any solution online, please help me out. I have imported the following files:

import java.awt.Canvas;
import java.awt.Graphics;
import javafx.scene.canvas.*;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.FileInputStream;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.paint.*;
2

There are 2 answers

0
Gabriel On

You aren't using the JavaFX canvas but the java.awt.Canvas, which doesn't have a constructor with two int values.

Try removing the java.awt.Canvas import.

0
Rans On

Make sure that the type of the Canvas is from the javafx.scene.canvas namespace and not from the java.awt namespace