0

I am creating a BarChart in JavaFX with random data, and I have a fxml file with a designated canvas that I want to draw the BarChart on.

I am fine on creating the bar chart, but if I have (for example) a barChart object of type BarChart and the canvas has fx:id "canvas", what is the method or code that lets me use GraphicsContext to draw the bar chart on the canvas? I know that to get the GraphicsContext it would be canvas.getGraphicsContext2D, but once I have that GraphicsContext object, what do I do with it to draw my barChart object on the canvas?

Ben
  • 129
  • 1
  • 1
  • 11

1 Answers1

2

You don't paint the BarChart on a Canvas. Both are of type Node. Just put the BarChart on your scene and feed it with data.

Roland
  • 18,114
  • 12
  • 62
  • 93
  • I will have the data fed into the BarChart before displaying it. I currently have the Canvas in the center of a BorderPane, so I want the BarChart to appear in the center node of that BorderPane. So are you saying it is impossible to put a BarChart on a Canvas? In that case I will probably go with the StackPane, as there are verified examples. My research supervisor suggested to use a Canvas, which was why I asked about Canvas specifically even though StackPane would be easier. – Ben Jun 30 '16 at 05:51
  • 2
    Well you could [snapshot the node](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#snapshot-javafx.scene.SnapshotParameters-javafx.scene.image.WritableImage-) to an image and [draw the image on a canvas](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/canvas/GraphicsContext.html#drawImage-javafx.scene.image.Image-double-double-), but that would be a silly idea, just follow Roland's much better suggestion. – jewelsea Jun 30 '16 at 06:08
  • Yeah I ended up just inserting my barChart into the center node of the borderPane and it worked. Also, @jewelsea I have to thank you because I ended up using your github code involving layered xy charts to help me get more familiar with creating BarCharts :) – Ben Jun 30 '16 at 09:08