n0obiscuitz
n0obiscuitz

Reputation: 573

Java&JFreeChart - How to set a JFreeChart's ChartPanel resize with it's container ( say JPanel )?

I just found that when i add a ChartPanel to a JFrame, the ChartPanel will resize to fit the frame as the JFrame dragged larger or smaller. However, when i add the ChartPanel to a JPanel, the JPanel's size( width and height ) changes to fit the JFrame as the JFrame resized. But the ChartPanel just keeps it's dimensions, leaving the enlarged JPanel a lot of empty space. How to make ChartPanel resize with it's container in GUI?

Here is my sample codes :

  1. This case the chart resize with the JFrame
ChartPanel chartPanel = new ChartPanel(createWhateverChart());
JFrame frame = new JFrame();
frame.add(chartPanel);
  1. In the case, i add the ChartPanel to JPanel first, for ease of management and update the chart but the ChartPanel doesn't resize with the JPanel/JFrame.
ChartPanel chartPanel = new ChartPanel(createWhateverChart());
JPanel panel = new JPanel("Who cares");
panel.add(chartPanel, BorderLayout.CENTER);
JFrame frame = new JFrame();
frame.add(panel);

Upvotes: 0

Views: 4437

Answers (1)

V-Q-A NGUYEN
V-Q-A NGUYEN

Reputation: 1707

Try my code and it works fine.

Note that :

I have one frame which contains a panelMain, A panelMain contains a subPanel and a subPanel contains ChartPanel.

frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));                      
JPanel panelMain = new JPanel(new GridLayout(0,2));            
ChartPanel chartPanel = createChart();        
JPanel subPanel = new JPanel(new BorderLayout());   
subPanel.setBorder(BorderFactory.createTitledBorder("Consommation"));
subPanel.setPreferredSize(new Dimension(400, 200));    
subPanel.add(chartPanel);   


panelMain.add(subPanel);        
frame.add(panelMain);        
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

And now when you resize your window application. Your chartPanel will resized automatically. Hope this helps.

Upvotes: 3

Related Questions