Java&JFreeChart - 如何使用其容器(例如JPanel)设置JFreeChart的ChartPanel大小调整?



我刚刚发现,当我在Jframe中添加ChartPanel时,ChartPanel将调整尺寸以适合框架,因为Jframe拖动更大或更小。但是,当我将ChartPanel添加到JPanel中时,JPANEL的大小(宽度和高度)会随着JFRAME调整大小而变化以适合Jframe。但是,图表板只会保持其尺寸,从而使jpanel放大了很多空白。如何使ChartPanel用GUI中的容器调整大小?

这是我的示例代码:

  1. 此情况使用JFRAME调整图表
ChartPanel chartPanel = new ChartPanel(createWhateverChart());
JFrame frame = new JFrame();
frame.add(chartPanel);
  1. 在这种情况下,我首先将ChartPanel添加到Jpanel,以易于管理和更新图表,但是ChartPanel不会与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);

尝试我的代码,并且效果很好。

请注意:

我有一个框架,其中包含一个面板,一个面板包含一个子板,一个子板包含图表板。

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);

现在,当您调整窗口应用程序大小时。您的ChartPanel将自动调整大小。希望这会有所帮助。

最新更新