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

不羁的心 提交于 2019-12-04 02:37:03

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/13229097/javajfreechart-how-to-set-a-jfreecharts-chartpanel-resize-with-its-containe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!