简体   繁体   中英

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);
}

}

您已经使用了注释@FXML因此在加载控制器时,Canvas已被初始化为“ fx:id ”(在FXML文件中),因此请尝试删除实例化,您可以直接使用带注释的canvas:

artHorizon = new Canvas(400, 400); // to delete

I think you should remove:

artHorizon = new Canvas(400, 400);

See if you can do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM