Search code examples
netbeansjpaneljfreechart

Adding a simple JFreeChart chart into a JPanel (netbeans gui)


I'm fairly new to Java and I've been trying to put a JFreeChart in a JPanel. I've finished the tutorial exercises where you generate a simple chart (with its own application window):

TimeSeriesChartDemo1

enter image description here

However I'm working on a larger group project that requires me to put the chart to be in a JPanel rather than its own window. The problem is I have no idea how to move from here, I also do not have the NetBeans IDE.

  1. What do I have to put in initComponents() to initialize the JPanel?
  2. Do I still have two files JFreeChartDemo.java and NetBeansGUI.java or is it all in one file?

If more information is needed please comment below.

For reference, I've cited a generic XYPlot example:


Solution

  • In your initComponents just initialize the JPanel (you can find plenty of information here). Once you have done that, all that you should do would be to add your chart to the JPanel. Once you have done that, just add the JPanel to the JFrame you are working with.

    So I am assuming you have something like so:

    public class JFreeChartDemo extends JFrame

    You should be able to get most of the work done if you do this:

    public class JFreeChartDemo extends JPanel

    This should allow you to re-use most of the initialization code, such as setting the size and location of the panel. You will however have to remove any JFrame related code from there.

    Finally, you should keep two seperate source files, one for the chart and one for the rest. I am assuming that in the NetBeansGUI class you are doing the rest of the GUI stuff, so you in your initComponent (in NetBeansGUI) you could also have:

    ...
    JFreeChartDemo jfd = new JFreeChartDemo()...
    ...
    this.getContentPane().add(jfd)
    

    In this case I am also assuming that NetBeansGUI extends JFrame.