我想在同一帧上显示许多图表,如下所示:
此示例来自java2s.com,但域已不存在。
实际上我是用这种方式做的,但是它不起作用,我只在框架中显示一张图表:
JFrame frame = new JFrame("Many charts same frame");
JFreeChart barChart1 =
ChartFactory.createHistogram("Histogram1","", "", dataset,
PlotOrientation.VERTICAL, true, true, false);
frame.getContentPane().add(new ChartPanel(barChart1));
JFreeChart barChart2 =
ChartFactory.createHistogram("Histogram2","", "", dataset,
PlotOrientation.VERTICAL, true, true, false);
frame.getContentPane().add(new ChartPanel(barChart2));
frame.pack();
frame.setVisible(true);
有什么想法吗?
答案 0 :(得分:2)
这是因为JFrame
默认使用BorderLayout
布局管理器。该布局管理器将容器分为五个区域,即CENTER,NORTH / PAGE_START,SOUTH / PAGE_END,WEST / LINE_START和EAST / LINE_END。 Take a look here.如果您只想将组件扔进容器中并让它为您组织它们,则可以使用FlowLayout
,它是JPanel
的默认布局管理器。尝试使用类似方法来更改JFrame
的布局管理器。
JFrame frame = new JFrame("Many charts same frame");
frame.setLayout( new FlowLayout() );
JFreeChart barChart1 =
ChartFactory.createHistogram("Histogram1","", "", dataset,
PlotOrientation.VERTICAL, true, true, false);
frame.getContentPane().add(new ChartPanel(barChart1));
JFreeChart barChart2 =
ChartFactory.createHistogram("Histogram2","", "", dataset,
PlotOrientation.VERTICAL, true, true, false);
frame.getContentPane().add(new ChartPanel(barChart2));
frame.pack();
frame.setVisible(true);
这样做可以解决您的问题。如果您想继续使用BorderLayout,则只需说出组件的插入位置,即在哪个区域。例如:
frame.getContentPane().add(new ChartPanel(barChart1), BorderLayout.NORTH);
frame.getContentPane().add(new ChartPanel(barChart2), BorderLayout.CENTER);
您也不需要使用getContentPane()
的{{1}}方法。从Java 5开始,如果我没有记错的话,您可以直接使用JFrame
方法。像这样:
add
下面是一个示例,向您展示这两个布局管理器之间的区别,看看:
frame.add(new ChartPanel(barChart1));