0

I am using Netbeans GUI builder to put a panel in a Jframe, where the size of the panel is set by me in the GUI builder. I'd like to embed a chart into this panel. Using answers from previous SO threads, I can achieve this behavior as follows:

ChartPanel p = new ChartPanel(chart);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setPreferredSize(new Dimension(400, 200));    
jPanel1.add(p, BorderLayout.CENTER);
jPanel1.validate();

Where I used setPreferredSize as a way to change the plot size. Otherwise, my plot is huge compared to the actual size I set on the panel. How can I have setPreferredSize infer the correct size from the panel dimension as created in the netbeans GUI? Right now, I have to manually pass a Dimension, which needs tuned each time I mess with the UI.

Thanks

HpTerm
  • 8,151
  • 12
  • 51
  • 67
Adam Hughes
  • 14,601
  • 12
  • 83
  • 122
  • 1
    [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Dec 16 '15 at 22:27
  • 1
    The problem is `ChartPanel` has it's own sizing requirements, which you are now ignoring – MadProgrammer Dec 16 '15 at 22:28
  • 1
    More [here](http://stackoverflow.com/a/10277372/230513). – trashgod Dec 17 '15 at 02:23
  • When I didn't use `setPreferredSize`, the plot was huge. I'll read into the links that were sent, thanks. But what are the ChartPanel requirements that I'm ignoring? – Adam Hughes Dec 17 '15 at 13:39

1 Answers1

0

What worked for me was to subclass ChartPanel and give it a no arguments constructor that just passes null to the super class.

public class MyChartPanel extends ChartPanel {

    public MyChartPanel() {
        super(null);
    }
}

Compile the file and you will then be able to drag the class from the Projects window to the GUI Designer and change the size within the gui panel.

One can also select the file in the Projects window and right-click for the pop-up menu and choose Tools -> Add to Palette ... to permanently add it to the GUI Designer palette for easier repeated use.

In my netbeans generated JFrame class's constructor I set the chart for the panel after initComponents() returns.

public MyJFrame() {
    initComponents();
    CategoryDataset dataset = createDataset(); // example custom application specific function for creating a dataset
    JFreeChart chart = createChart(dataset); // example custom application specific function for creating JFreeChart
    this.myChartPanel1.setChart(chart);
}
WillShackleford
  • 6,918
  • 2
  • 17
  • 33