pdel
pdel

Reputation: 705

Multiple JFreeCharts on a window

I'm trying to get multiple jfreecharts displaying within a single window. Apparently this is not possible with the included ChartFrame so I attempted to add multiple copies of the same chart to a JFrame which didn't work. Any ideas?

JFrame frame = new JFrame("Chart");
frame.getContentPane().add(new ChartPanel(chart1));
frame.getContentPane().add(new ChartPanel(chart2));
frame.pack();
frame.setVisible(true);

With this code, I only get one chart in the JFrame.

EDIT: I added another data set and chart but it still only displays one of them.

Upvotes: 1

Views: 4945

Answers (2)

Nestor
Nestor

Reputation: 756

Cause of your problem is layout of frame.getContentPane(). Default layout at the JFrame content pane - BorderLayout. Read more about BorderLayout here. This operation

frame.getContentPane().add(new ChartPanel(chart));

equals

frame.getContentPane().add(new ChartPanel(chart), BorderLayout.CENTER);

and add ChartPanel to the CENTER area of the content pane. Second ChartPanel you add to CENTER area too. Then you add two component to the same area the last added one hides all previous added. Thus second ChartPanel hides first one.

You need change layout for frame.getContentPane().

You may use the same chart to two ChartPanel. Try to change you code to

JFrame frame = new JFrame("Chart");
frame.getContentPane().add(new ChartPanel(chart), BorderLayout.WEST);
frame.getContentPane().add(new ChartPanel(chart), BorderLayout.EAST);
frame.pack();
frame.setVisible(true);

It is not code for production. It just example to show two ChartPanel on the frame.

Upvotes: 5

Dan D.
Dan D.

Reputation: 32391

You need to have different chart instances. If you use the same reference, the last one that is added to a ChartPanel will be displayed.

Upvotes: 1

Related Questions