简体   繁体   English

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

[英]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. 我刚刚发现,当我将ChartPanel添加到JFrame时,随着JFrame拖动的变大或变小,ChartPanel将调整大小以适合框架。 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. 但是,当我将ChartPanel添加到JPanel时,随着JFrame调整大小,JPanel的大小(width和height)会更改以适合JFrame。 But the ChartPanel just keeps it's dimensions, leaving the enlarged JPanel a lot of empty space. 但是,ChartPanel仅保留其尺寸,从而使扩大的JPanel留有很多空白空间。 How to make ChartPanel resize with it's container in GUI? 如何在GUI中使用ChartPanel的容器调整大小?

Here is my sample codes : 这是我的示例代码:

  1. This case the chart resize with the JFrame 这种情况下,图表使用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添加到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); 

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. 我有一帧包含一个panelMain,panelMain包含一个subPanel,一个subPanel包含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. 您的chartPanel会自动调整大小。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM