Monday, July 1, 2013

JFreeChart - Dynamic Chart Example

Hello Friends,

I'm back again with one of the example of JFreeChart, one of the widely used charting APIs in Java.

 This is the simple example illustrates the power of Java Charting using JFreeCharts.

 This example has following features:
  •   Displays Students Results in line chart.
  •   X-Axis corresponds to Subjects
  •  Y-Axis corresponds to Marks secured
  •  Each line that is plot on the chart represents each student.
  •  Chart is dynamically populated from the values extracted from database.
  •  Student Wise Dropdown is present

Following is the Code For the example,

package com.mayuri.example;
   
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;

public class ChartDemoAppletDb extends JApplet {
ChartPanel chartPanel;
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    @Override
    public void init() {
        createDataset("All");
        chartPanel = createChart();
        chartPanel.setMouseWheelEnabled(true);
        chartPanel.setHorizontalAxisTrace(true);
        chartPanel.setVerticalAxisTrace(true);
        chartPanel.setZoomTriggerDistance(10);
        setLayout(new BorderLayout(0, 5));
        add(chartPanel, BorderLayout.CENTER);
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        panel.add(studentsWise());
        panel.add(restoreZoom());
        panel.add(enableTrace());
        panel.add(disableTrace());
        add(panel, BorderLayout.SOUTH);
    }
private JButton restoreZoom() {
        final JButton restore = new JButton(new AbstractAction("Restore") {
            @Override
            public void actionPerformed(ActionEvent e) {
                chartPanel.restoreAutoBounds();
            }
        });
        return restore;
    }


private JButton enableTrace() {
        final JButton traceEnabled = new JButton(new AbstractAction("Enable Trace") {
            @Override
            public void actionPerformed(ActionEvent e) {
                 chartPanel.setHorizontalAxisTrace(true);
                 chartPanel.setVerticalAxisTrace(true);
                 chartPanel.repaint();
            }
        });
        return traceEnabled;
    }
private JButton disableTrace() {
        final JButton traceDisabled = new JButton(new AbstractAction("Disable Trace") {
            @Override
            public void actionPerformed(ActionEvent e) {
                 chartPanel.setHorizontalAxisTrace(false);
                 chartPanel.setVerticalAxisTrace(false);
                 chartPanel.repaint();
            }
        });
        return traceDisabled;
    }
private JComboBox studentsWise() {
        final JComboBox studentsNames = new JComboBox();
        ArrayList<String> studNameList = new ArrayList<String>();
        DataProvider dataProvide = new DataProvider();
        studNameList = dataProvide.getStudentsNames();
        studentsNames.setModel(new DefaultComboBoxModel(studNameList.toArray()));
        studentsNames.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if ("All".equals(studentsNames.getSelectedItem())) {
                dataset.clear();
                 createDataset("All");
                } else {
                    String selstudname = studentsNames.getSelectedItem().toString();
                    dataset.clear();
                    createDataset(selstudname);
                }
            }
        });
        return studentsNames;
    }
     private ChartPanel createChart() {
        JFreeChart chart = ChartFactory.createLineChart(
            "Students Results",
            "Subjects",
            "Marks",
            dataset,
            PlotOrientation.VERTICAL,
            true,
            true,
            false
            );       
        chart.setBackgroundPaint(Color.PINK);
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.CYAN);
        plot.setRangeGridlinePaint(Color.BLACK);
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        renderer.setShapesVisible(true);
        renderer.setDrawOutlines(true);
        renderer.setUseFillPaint(true);
        return new ChartPanel(chart);
    }
private void createDataset(String condition) {
        Connection connect = null;
        ResultSet resultSet = null;
  try{
    DataProvider dataProvide = new DataProvider();
    connect = dataProvide.getDbConnection();
    String query = null;
    if("All".equals(condition)){
    query="SELECT * from APP.STUDENTS";
    } else {
    query="SELECT * from APP.STUDENTS WHERE STUDNAME = '"+condition+"'";
    }  

    PreparedStatement statement = connect.prepareStatement(query);
      resultSet = statement.executeQuery();
      while (resultSet.next()) {
        String studname = resultSet.getString("studname");
        String physics = resultSet.getString("physics");
        String chemistry = resultSet.getString("chemistry");
        String biology = resultSet.getString("biology");
        dataset.addValue(Integer.parseInt(physics), studname, "physics");
        dataset.addValue(Integer.parseInt(chemistry), studname, "chemistry");
        dataset.addValue(Integer.parseInt(biology), studname, "biology");
      }
      }catch(Exception e) {
          e.printStackTrace();
      }
    }
}

    class DataProvider {
        public Connection getDbConnection(){
        Connection con = null;
        try{
            Class.forName("<JDBC Driver>").newInstance();
            String url = "<DB URL>";
            con = DriverManager.getConnection(url);
            }
        catch(Exception e){
            e.printStackTrace();
        }
        return con;
    }

    public ArrayList<String> getStudentsNames(){
        ArrayList<String> studNameList = new ArrayList<String>();
        Connection connect = getDbConnection();
        ResultSet resultSet = null;
        try{
            studNameList.add("All");
            Statement stmt = connect.createStatement();
            String query = "SELECT STUDNAME from APP.STUDENTS ";
            resultSet = stmt.executeQuery(query);
            while(resultSet.next()){
                studNameList.add(resultSet.getString("studname"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return studNameList;
    }
}

Screenshots For the Database Table and output for the above code is as follows,





 I hope this example will be useful to to some of people Googling about JFreeChart :)

Happy Coding!

~Mayuri 

No comments:

Animated Container in Flutter

Please check this flutter video tutorial for detailed example and implementation of Animated Container in Flutter.