How to use panels from third parties (Jfreechart) in netbeans GUI builder

By | 3. November 2015

The netbeans GUI builder is a very convenient way to design user interfaces. But when you want to implement interface containers from third parties it becomes more complicated: you can’t draw these containers into the design space and access them easily in your source code. Another problem is that the NetBeans GUI editor generates a lot of code in the background which will be overwritten again when you try to change it:

Bildschirmfoto 2015-11-03 um 22.31.51

But there is a possibilty to modify parts of the code, to connect e.g. to third party panels like ChartPanel from Jfreechart. At first you should create a global ChartPanel in your source code. Then you should have a look at the constructor that creates the new form. If you want to make adaptions to your global ChartPanel you have to do it before the initComponents() method is called:

public class UI_ShowDownloadedQuotes extends javax.swing.JDialog {

// Make it global
static ChartPanel panel ;

/**
* Constructor creates new form UI_ShowDownloadedQuotes
*/
public UI_ShowDownloadedQuotes(java.awt.Frame parent, boolean modal) {
super(parent, modal);

// Must be before initComponents();
JFreeChart chart = createChart(createDataset());
panel = new ChartPanel(chart);
panel.setFillZoomRectangle(true);
panel.setMouseWheelEnabled(true);

initComponents();

}

...

This still not works because the initComponents() method still contains editor generated code which is not related to your ChartPanel yet. The initComponents() method is where all the configuration of layouts etc. is done.

Now add a JPanel by drag and drop into your GUI with the GUI editor of NetBeans. Then do a right click on it and choose “customize code”:

Bildschirmfoto 2015-11-03 um 22.43.36

In the ComboBox choose “custom creation” and change the code so that it points to the ChartPanel panel:

Bildschirmfoto 2015-11-03 um 22.44.53

If you run the program now the ChartPanel will be displayed in the JPanel of the dialog:

Bildschirmfoto 2015-11-03 um 22.47.22