Search code examples
javaswingjfreechartzooming

Zoom In and Zoom out functionality on a button click on JfreeChart line graph?


Basically i want the line graph to be zoomed in and Zoomed out(total 4 buttons,2 for X-axis(Zoom in and Zoom out) and other two for Y-axis) on a button click along any axis like if the graph drawn on negative x-axis and negative Y-axis area ,depending on data points then on button click the graph should be Zoomed in and Zoomed out along that negative x-axis or negative Y-axis based on button click.

How can i achieve this ?Any sample code with detail Explanation is much helpful!!

 private JButton createZoom()
 {
        final JButton auto = new JButton("ZOOMIN");
        auto.setActionCommand("ZOOM_IN_DOMAIN");
        auto.addActionListener(new ChartPanel(chart));
        return auto;
    }

Solution

  • Each button's Action implementation should invoke the corresponding method used by ChartPanel to create it's popup menu of zoom commands. The implementation of actionPerformed() is a convenient guide to the available zooming functionality. For example, the ZOOM_IN_DOMAIN_COMMAND is handled by invoking zoomInDomain(). Based on this example, a typical Zoom X handler relative to the origin is shown below:

    private JButton createZoom() {
        final JButton zoomX = new JButton(new AbstractAction("Zoom X") {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                chartPanel.zoomInDomain(0, 0);
            }
        });
        return zoomX;
    }
    

    If the default zoomPoint is sufficient, you can use the chart panel's implementation:

    private JButton createZoom() {
        final JButton zoomX = new JButton("Zoom X");
        zoomX.setActionCommand(ChartPanel.ZOOM_IN_DOMAIN_COMMAND);
        zoomX.addActionListener(chartPanel);
        return zoomX;
    }
    

    zoomed image

    In contrast, the createZoom() method in the original example shows how to evoke the ChartPanel method restoreAutoBounds(), which restores the auto-range calculation on both axes.

    image