05 December 2014

Java swing chart library

First You need to download library.(http://www.jfree.org/jfreechart/download.html).Then it supports different type of chart types and it is easy to implement.Here i will describe how to implement PieChart and save chart as Image.Before You start you have to import jcommon and jfreechart to your project.

public class PieChartExampleDemo extends JFrame {

    public PieChartExampleDemo(String applicationTitle, String chartTitle) {

        super(applicationTitle);

        PieDataset dataset = createDataset();

        JFreeChart chart = createChart(dataset, chartTitle);

        String filename = "F:\\pichartImage.jpg";

        try {

            ChartUtilities.saveChartAsJPEG(new File(filename), chart, 600, 400);

        } catch (IOException e) {

            e.printStackTrace();

        }

        ChartPanel chartPanel = new ChartPanel(chart);

        chartPanel.setPreferredSize(new java.awt.Dimension(600, 400));

        setContentPane(chartPanel);


    }


    private  PieDataset createDataset() {

        DefaultPieDataset result = new DefaultPieDataset();

        result.setValue("Blackberry", 24);

        result.setValue("Apple", 22);

        result.setValue("Windows", 44);

        result.setValue("Android", 35);

        result.setValue("Symbian", 5);

        result.setValue("Other", 4);

        return result;


    }


    private JFreeChart createChart(PieDataset dataset, String title) {

        JFreeChart chart = ChartFactory.createPieChart3D(title, dataset,

                true,

                true,

                false);

        PiePlot3D plot = (PiePlot3D) chart.getPlot();

        plot.setStartAngle(290);

        plot.setDirection(Rotation.CLOCKWISE);

        plot.setForegroundAlpha(0.5f);

        return chart;

    }

}

From main class you can call to this class.You can save chart as jpg image.

PieChartExampleDemo pieChartExampleDemo = new PieChartExampleDemo("Mobile OS", "Mobile operating System Usage 2014");
        pieChartExampleDemo.pack();
        pieChartExampleDemo.setVisible(true);


And This is the result.



No comments:

Post a Comment