2

I have a JFrame frame which contains a JPanel panel. I also added a JFreeChart ChartPanel cp to the panel. What I did so far is using a ComponentListener on my frame frame to react on resizing the window.

Here is my code snippet:

private void initialize() throws ParseException {
    frame = new JFrame();
    frame.addComponentListener(new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent e) {
            ChartPanel cp = (ChartPanel)panel.getComponents()[0];
            cp.setPreferredSize(new java.awt.Dimension(panel.getWidth(), panel.getHeight()));
            frame.repaint();
            cp.repaint();
        }

        @Override
        public void componentMoved(ComponentEvent e) {}

        @Override
        public void componentShown(ComponentEvent e) {}

        @Override
        public void componentHidden(ComponentEvent e) {}
    });

    ...
}

The ChartPanel is resized perfectly when changing the size of the frame. But when I maximize my frame the chart panel won't change it's size! It stays at the same same as it is at the moment before maximizing. Therefore when I "un-maximize" my frame again, the chart panel is maximized and this leads to the problem, that the chart won't fit into the chart panel anymore. All this resize thing seems to be "one step behind"...

Does anyone know this behavior and help how to correct it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
D. Müller
  • 3,336
  • 4
  • 36
  • 84

1 Answers1

1

Calling ChartPanel.setSize after ChartPanel.setPreferredSize and JFrame.validate did the job! See the new code:

frame = new JFrame();
frame.addComponentListener(new ComponentListener() {
    @Override
    public void componentResized(ComponentEvent e) {
        // frame.repaint();
        ChartPanel cp = (ChartPanel)panel.getComponents()[0];
        cp.setPreferredSize(new java.awt.Dimension(panel.getWidth(), panel.getHeight()));
        cp.setSize(new java.awt.Dimension(panel.getWidth(), panel.getHeight()));
        // frame.invalidate();
        frame.validate();
        // frame.repaint();
    }
    ...
});
...
D. Müller
  • 3,336
  • 4
  • 36
  • 84