Example usage for org.jfree.data.general DefaultPieDataset setValue

List of usage examples for org.jfree.data.general DefaultPieDataset setValue

Introduction

In this page you can find the example usage for org.jfree.data.general DefaultPieDataset setValue.

Prototype

public void setValue(Comparable key, double value) 

Source Link

Document

Sets the data value for a key and sends a DatasetChangeEvent to all registered listeners.

Usage

From source file:org.pentaho.chart.plugin.jfreechart.JFreeChartFactoryEngine.java

public JFreeChart makePieChart(ChartModel chartModel, NamedValuesDataModel dataModel,
        final IChartLinkGenerator linkGenerator) {
    final DefaultPieDataset dataset = new DefaultPieDataset();
    for (NamedValue namedValue : dataModel) {
        if (namedValue.getName() != null) {
            dataset.setValue(namedValue.getName(),
                    scaleNumber(namedValue.getValue(), dataModel.getScalingFactor()));
        }//from w ww . j  av  a2s. c o  m
    }

    boolean showLegend = (chartModel.getLegend() != null) && (chartModel.getLegend().getVisible());

    String title = "";
    if ((chartModel.getTitle() != null) && (chartModel.getTitle().getText() != null)
            && (chartModel.getTitle().getText().trim().length() > 0)) {
        title = chartModel.getTitle().getText();
    }

    final JFreeChart chart = ChartFactory.createPieChart(title, dataset, showLegend, true, false);

    initChart(chart, chartModel);

    final PiePlot jFreePiePlot = (PiePlot) chart.getPlot();

    if (linkGenerator != null) {
        jFreePiePlot.setURLGenerator(new PieURLGenerator() {

            public String generateURL(PieDataset arg0, Comparable arg1, int arg2) {
                return linkGenerator.generateLink(arg1.toString(), arg1.toString(), arg0.getValue(arg1));
            }
        });
    }

    jFreePiePlot.setNoDataMessage("No data available"); //$NON-NLS-1$
    jFreePiePlot.setCircular(true);
    jFreePiePlot.setLabelGap(0.02);

    org.pentaho.chart.model.PiePlot chartBeansPiePlot = (org.pentaho.chart.model.PiePlot) chartModel.getPlot();

    List<Integer> colors = getPlotColors(chartBeansPiePlot);

    int index = 0;
    for (NamedValue namedValue : dataModel) {
        if (namedValue.getName() != null) {
            jFreePiePlot.setSectionPaint(namedValue.getName(),
                    new Color(0x00FFFFFF & colors.get(index % colors.size())));
        }
        index++;
    }

    if (chartBeansPiePlot.getLabels().getVisible()) {
        jFreePiePlot.setLabelGenerator(new StandardPieSectionLabelGenerator());

        Font font = ChartUtils.getFont(chartBeansPiePlot.getLabels().getFontFamily(),
                chartBeansPiePlot.getLabels().getFontStyle(), chartBeansPiePlot.getLabels().getFontWeight(),
                chartBeansPiePlot.getLabels().getFontSize());
        if (font != null) {
            jFreePiePlot.setLabelFont(font);
            if (chartBeansPiePlot.getLabels().getColor() != null) {
                jFreePiePlot.setLabelPaint(new Color(0x00FFFFFF & chartBeansPiePlot.getLabels().getColor()));
            }
            if (chartBeansPiePlot.getLabels().getBackgroundColor() != null) {
                jFreePiePlot.setLabelBackgroundPaint(
                        new Color(0x00FFFFFF & chartBeansPiePlot.getLabels().getBackgroundColor()));
            }
        }
    } else {
        jFreePiePlot.setLabelGenerator(null);
    }

    jFreePiePlot.setStartAngle(-chartBeansPiePlot.getStartAngle());

    return chart;
}

From source file:org.openmrs.web.controller.ConceptStatsFormController.java

/**
 * Called prior to form display. Allows for data to be put in the request to be used in the view
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
 *//* w w  w .java 2s.  c  om*/
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    if (!Context.hasPrivilege("View Observations")) {
        return map;
    }

    MessageSourceAccessor msa = getMessageSourceAccessor();
    Locale locale = Context.getLocale();
    ConceptService cs = Context.getConceptService();
    String conceptId = request.getParameter("conceptId");
    //List<Obs> obs = new Vector<Obs>();
    //List<Obs> obsAnswered = new Vector<Obs>();

    if (conceptId != null) {
        Concept concept = cs.getConcept(Integer.valueOf(conceptId));
        ObsService obsService = Context.getObsService();

        if (concept != null) {

            // previous/next ids for links
            map.put("previousConcept", cs.getPrevConcept(concept));
            map.put("nextConcept", cs.getNextConcept(concept));

            //obs = obsService.getObservations(concept, "valueNumeric, obsId");
            //obsAnswered = obsService.getObservationsAnsweredByConcept(concept);

            if (ConceptDatatype.NUMERIC.equals(concept.getDatatype().getHl7Abbreviation())) {
                map.put("displayType", "numeric");

                List<Obs> numericAnswers = obsService.getObservations(null, null,
                        Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null,
                        Collections.singletonList("valueNumeric"), null, null, null, null, false);

                if (numericAnswers.size() > 0) {
                    Double min = numericAnswers.get(0).getValueNumeric();
                    Double max = (Double) numericAnswers.get(numericAnswers.size() - 1).getValueNumeric();
                    Double median = (Double) numericAnswers.get(numericAnswers.size() / 2).getValueNumeric();

                    Map<Double, Integer> counts = new HashMap<Double, Integer>(); // counts for the histogram
                    Double total = 0.0; // sum of values. used for mean

                    // dataset setup for lineChart
                    TimeSeries timeSeries = new TimeSeries(concept.getName().getName(), Day.class);
                    TimeSeriesCollection timeDataset = new TimeSeriesCollection();
                    Calendar calendar = Calendar.getInstance();

                    // array for histogram
                    double[] obsNumerics = new double[(numericAnswers.size())];

                    Integer i = 0;
                    for (Obs obs : numericAnswers) {
                        Date date = (Date) obs.getObsDatetime();
                        Double value = (Double) obs.getValueNumeric();

                        // for mean calculation
                        total += value;

                        // for histogram
                        obsNumerics[i++] = value;
                        Integer count = counts.get(value);
                        counts.put(value, count == null ? 1 : count + 1);

                        // for line chart
                        calendar.setTime(date);
                        Day day = new Day(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH) + 1, // January = 0 
                                calendar.get(Calendar.YEAR) < 1900 ? 1900 : calendar.get(Calendar.YEAR) // jfree chart doesn't like the 19th century
                        );
                        timeSeries.addOrUpdate(day, value);
                    }

                    Double size = new Double(numericAnswers.size());
                    Double mean = total / size;

                    map.put("size", numericAnswers.size());
                    map.put("min", min);
                    map.put("max", max);
                    map.put("mean", mean);
                    map.put("median", median);

                    // create histogram chart
                    HistogramDataset histDataset = new HistogramDataset(); // dataset for histogram
                    histDataset.addSeries(concept.getName().getName(), obsNumerics, counts.size());

                    JFreeChart histogram = ChartFactory.createHistogram(concept.getName().getName(),
                            msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                            msa.getMessage("Concept.stats.histogramRangeAxisTitle"), histDataset,
                            PlotOrientation.VERTICAL, false, true, false);
                    map.put("histogram", histogram);

                    if (size > 25) {
                        // calculate 98th percentile of the data:
                        Double x = 0.98;
                        Integer xpercentile = (int) (x * size);
                        Double upperQuartile = numericAnswers.get(xpercentile).getValueNumeric();
                        Double lowerQuartile = numericAnswers.get((int) (size - xpercentile)).getValueNumeric();
                        Double innerQuartile = upperQuartile - lowerQuartile;
                        Double innerQuartileLimit = innerQuartile * 1.5; // outliers will be greater than this from the upper/lower quartile
                        Double upperQuartileLimit = upperQuartile + innerQuartileLimit;
                        Double lowerQuartileLimit = lowerQuartile - innerQuartileLimit;

                        List<Obs> outliers = new Vector<Obs>();

                        // move outliers to the outliers list
                        // removing lower quartile outliers
                        for (i = 0; i < size - xpercentile; i++) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() >= lowerQuartileLimit) {
                                break; // quit if this value is greater than the lower limit
                            }
                            outliers.add(possibleOutlier);
                        }

                        // removing upper quartile outliers
                        for (i = size.intValue() - 1; i >= xpercentile; i--) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() <= upperQuartileLimit) {
                                break; // quit if this value is less than the upper limit
                            }
                            outliers.add(possibleOutlier);
                        }
                        numericAnswers.removeAll(outliers);

                        double[] obsNumericsOutliers = new double[(numericAnswers.size())];
                        i = 0;
                        counts.clear();
                        for (Obs values : numericAnswers) {
                            Double value = values.getValueNumeric();
                            obsNumericsOutliers[i++] = value;
                            Integer count = counts.get(value);
                            counts.put(value, count == null ? 1 : count + 1);
                        }

                        // create outlier histogram chart
                        HistogramDataset outlierHistDataset = new HistogramDataset();
                        outlierHistDataset.addSeries(concept.getName().getName(), obsNumericsOutliers,
                                counts.size());

                        JFreeChart histogramOutliers = ChartFactory.createHistogram(concept.getName().getName(),
                                msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                                msa.getMessage("Concept.stats.histogramRangeAxisTitle"), outlierHistDataset,
                                PlotOrientation.VERTICAL, false, true, false);
                        map.put("histogramOutliers", histogramOutliers);
                        map.put("outliers", outliers);

                    }

                    // create line graph chart
                    timeDataset.addSeries(timeSeries);
                    JFreeChart lineChart = ChartFactory.createTimeSeriesChart(concept.getName().getName(),
                            msa.getMessage("Concept.stats.lineChartDomainAxisLabel"),
                            msa.getMessage("Concept.stats.lineChartRangeAxisLabel"), timeDataset, false, true,
                            false);
                    map.put("timeSeries", lineChart);

                }
            } else if (ConceptDatatype.BOOLEAN.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create bar chart for boolean answers
                map.put("displayType", "boolean");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Boolean answer = o.getValueAsBoolean();
                    if (answer == null) {
                        answer = false;
                    }
                    String name = answer.toString();
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            } else if (ConceptDatatype.CODED.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create pie graph for coded answers
                map.put("displayType", "coded");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Concept value = o.getValueCoded();
                    String name;
                    if (value == null) {
                        name = "[value_coded is null]";
                    } else {
                        name = value.getName().getName();
                    }
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            }
        }

    }

    //map.put("obs", obs);
    //map.put("obsAnswered", obsAnswered);

    map.put("locale", locale.getLanguage().substring(0, 2));

    return map;
}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getProvincePie(Session s) {
    JFreeChart chart;/*from   www .j ava 2 s  .c o m*/
    String[] provinces = { "PE", "YT", "NT", "NU", "ON", "QC", "AB", "BC", "NL", "MB", "NB", "NS", "SK" };
    DefaultPieDataset ds = new DefaultPieDataset();
    String query = "select count(*) from UserModel as u where u.province=?";

    int total = 0;
    for (String province : provinces) {
        Integer integer = ((Long) s.createQuery(query).setString(0, province).list().get(0)).intValue();
        total += integer;
        ds.setValue(province, integer);
    }

    chart = ChartFactory.createPieChart("Province Breakdown (for " + total + " known addresses)", ds, false,
            false, false);

    PiePlot plot = ((PiePlot) chart.getPlot());
    StandardPieItemLabelGenerator n = new StandardPieItemLabelGenerator("{0} = {1} ({2})",
            new DecimalFormat("0"), new DecimalFormat("0.0%"));
    plot.setLabelGenerator(n);
    return chart;
}

From source file:info.mikaelsvensson.devtools.analysis.localaccesslog.LocalAccessLogReportGenerator.java

@Override
public void generateReport(File outputFile, ReportPrinter reportPrinter) throws FileNotFoundException {
    final PrintStream ps = new PrintStream(outputFile);
    final Collection<LocalAccessLogSample> allSamples = _log.getSamples();
    Map<String, Collection<LocalAccessLogSample>> samplesByTestSession = SampleCollector.COLLECTOR_BY_SESSION_DATE
            .getFilteredAndGrouped(allSamples);
    for (Map.Entry<String, Collection<LocalAccessLogSample>> sessionEntry : samplesByTestSession.entrySet()) {
        final Collection<LocalAccessLogSample> sessionSamples = sessionEntry.getValue();
        Map<String, Collection<LocalAccessLogSample>> samples = SAMPLE_COLLECTOR
                .getFilteredAndGrouped(sessionSamples);
        String[][] data = new String[samples.size() + 1][];
        int i = 0;
        int sumCount = 0;
        final DefaultPieDataset dataset = new DefaultPieDataset();
        final JFreeChart chart = ChartFactory.createPieChart(
                "Status Codes For Session " + sessionEntry.getKey(), dataset, true, false, Locale.ENGLISH);
        final File chartFile = new File(outputFile.getAbsolutePath() + "."
                + StringUtils.remove(sessionEntry.getKey(), ':').replace(' ', '-') + ".png");
        final PiePlot plot = (PiePlot) chart.getPlot();
        for (Map.Entry<String, Collection<LocalAccessLogSample>> entry : samples.entrySet()) {
            final Collection<LocalAccessLogSample> responseCodeSamples = entry.getValue();
            final int count = responseCodeSamples.size();
            data[i++] = new String[] { entry.getKey(), ToStringUtil.toString(count),
                    ToStringUtil.toString(_log.calculateAverage(responseCodeSamples)),
                    ToStringUtil.toString(_log.calculateMin(responseCodeSamples)),
                    ToStringUtil.toString(_log.calculateMax(responseCodeSamples)) };
            sumCount += count;//ww  w . java 2 s.  c  om

            final String label = entry.getKey() + " (" + count + " reqs)";
            dataset.setValue(label, count);
            plot.setSectionPaint(label, entry.getKey().equals("200") ? Color.GREEN : Color.RED);
        }
        data[i] = new String[] { "All", ToStringUtil.toString(sumCount),
                ToStringUtil.toString(_log.calculateAverage(sessionSamples)),
                ToStringUtil.toString(_log.calculateMin(sessionSamples)),
                ToStringUtil.toString(_log.calculateMax(sessionSamples)) };

        reportPrinter.printTable(ps, sessionEntry.getKey(), 10,
                new String[] { "Status Code", "# Requests", "Avg [ms]", "Min [ms]", "Max [ms]" }, data, null);

        if (sumCount > NUMBER_OF_REQUESTS_IN_SHORT_TEST) {
            try {
                ChartUtilities.saveChartAsPNG(chartFile, chart, 500, 500);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
    ps.close();
}

From source file:org.talend.dataprofiler.chart.TOPChartService.java

@Override
public Object createDatasetForDuplicateRecord(Map<String, Long> dupStats) {
    if (dupStats != null) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        Iterator<String> iterator = dupStats.keySet().iterator();
        while (iterator.hasNext()) {
            String label = iterator.next();
            dataset.setValue(label, dupStats.get(label));
        }//from   www .jav a  2  s . com
        return dataset;
    }
    return null;
}

From source file:vn.edu.vttu.ui.PanelStatiticsService.java

private void showChart() {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DefaultPieDataset dataset = new DefaultPieDataset();
    int row = tbResult.getRowCount();
    for (int i = 0; i < row; i++) {
        totalNumber = totalNumber + Integer.parseInt(String.valueOf(tbResult.getValueAt(i, 3)));
    }/*w  ww.jav  a2 s .  c  o  m*/
    for (int i = 0; i < row; i++) {
        double value = 0;
        try {
            try {
                value = Double
                        .parseDouble(String.valueOf(tbResult.getValueAt(i, 3)).trim().replaceAll("\\.", ""));
            } catch (Exception e) {
                value = Double
                        .parseDouble(String.valueOf(tbResult.getValueAt(i, 3)).trim().replaceAll(",", ""));
            }
        } catch (Exception e) {
            value = 0;
        }
        String name = String.valueOf(tbResult.getValueAt(i, 1)).trim();
        DecimalFormat df = new DecimalFormat("###,##");
        value = (value / totalNumber) * 100;
        System.out.println(totalNumber);
        dataset.setValue(name, value);
    }

    JFreeChart chart = ChartFactory.createPieChart3D("TH?NG K T L S DNG DCH V", dataset,
            true, true, true);
    PiePlot3D p = (PiePlot3D) chart.getPlot();
    p.setNoDataMessage("Khng c d liu thng k");
    ChartPanel CP = new ChartPanel(chart);
    pnChart.removeAll();
    pnChart.add(CP);
    pnChart.updateUI();
    pnChart.repaint();
    //ChartFrame frame = new ChartFrame("Thng k doanh thu", chart);
    //frame.setSize(450, 350);
    //frame.setVisible(true);
}

From source file:org.gridchem.client.gui.charts.UsageChart.java

/**
 * Returns a dataset representing the cumulative usage of each user
 * across the set of projects.  /*from  www . j a  va  2s.c o  m*/
 * 
 * @param projectCollabTable
 * @return
 */
private DefaultPieDataset createUserDataset(Hashtable<ProjectBean, List<CollaboratorBean>> usageTable,
        CollaboratorBean collab) {

    DefaultPieDataset pds = new DefaultPieDataset();

    Hashtable<String, Double> userUsageTable = new Hashtable<String, Double>();

    // for every project 
    for (ProjectBean project : usageTable.keySet()) {
        // if the user is part of this project
        if (usageTable.get(project).contains(collab)) {
            userUsageTable.put(project.getName(), usageTable.get(project)
                    .get(usageTable.get(project).indexOf(collab)).getTotalUsage().getUsed());
        }
    }

    // now put the tallies in the dataset
    for (String userName : userUsageTable.keySet()) {
        pds.setValue(userName, userUsageTable.get(userName).doubleValue());
    }

    return pds;
}

From source file:GUI.GUI_reporting.java

private void btnLancerStatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLancerStatActionPerformed
    // TODO add your handling code here:

    // faire la requete sql et ranger les variables aux bon endroits
    JDialog reponse = new JDialog();
    DefaultPieDataset pieDataset = new DefaultPieDataset();
    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    String text = "";
    String Infox = "";
    String Infoy = "";
    switch (action) {//////////////////:Pie charts//////////////////////////////////////
    case 1://from www .  j av a 2 s  .co  m
        //set values
        pieDataset.setValue("de 700  1100", getEmployeParSalaire(1));
        pieDataset.setValue("de 1100  1300", getEmployeParSalaire(2));
        pieDataset.setValue("de 1300  1700", getEmployeParSalaire(3));
        pieDataset.setValue("Plus de 1700", getEmployeParSalaire(4));
        text = "Nombre d'employs par tranche de salaire";
        break;

    case 2:
        //set values
        pieDataset.setValue("REA", getEmployeParService(1));
        pieDataset.setValue("CHG", getEmployeParService(2));
        pieDataset.setValue("CAR", getEmployeParService(3));
        text = "Nombre d'employs par service";
        break;
    case 3:
        //set values
        pieDataset.setValue("Anesthesiste", getEmployeParSpecialite(1));
        pieDataset.setValue("Cardiologue", getEmployeParSpecialite(2));
        pieDataset.setValue("Generaliste", getEmployeParSpecialite(3));
        pieDataset.setValue("Orthopediste", getEmployeParSpecialite(4));
        pieDataset.setValue("Pneumologue", getEmployeParSpecialite(5));
        pieDataset.setValue("Radiologue", getEmployeParSpecialite(6));
        pieDataset.setValue("Traumatologue", getEmployeParSpecialite(7));
        text = "Nombre d'employs par spcialit";
        break;
    case 4:
        //set values
        pieDataset.setValue("Jour", getEmployeRotation(1));
        pieDataset.setValue("Nuit", getEmployeRotation(2));
        text = "Nombre d'employs par rotation";
        break;
    /// diagrammes en barre/////////////////////////////
    case 5:
        //dataset.addValue(WIDTH, WIDTH, action);
        final String REA = "Moyenne pour REA";
        final String CHG = "Moyenne pour CHG";
        final String CAR = "Moyenne pour CAR";
        final String salaire = "salaire";
        dataset.addValue(getSalaireParService(1), salaire, REA);
        dataset.addValue(getSalaireParService(2), salaire, CHG);
        dataset.addValue(getSalaireParService(3), salaire, CAR);
        Infox = "service";
        Infoy = "salaire";
        text = "Salaire moyen par service";
        break;

    case 6:
        //set values
        final String malade = "Malade";
        final String rea = "REA";
        final String chg = "CHG";
        final String car = "CAR";
        dataset.addValue(getMaladeParService(1), malade, rea);
        dataset.addValue(getMaladeParService(2), malade, chg);
        dataset.addValue(getMaladeParService(3), malade, car);
        Infox = "Service";
        Infoy = "Nombre de malades";
        text = "Nombre de malade par service";
        break;
    case 7:
        //set values
        final String MAAF = "MAAF";
        final String MNAM = "MNAM";
        final String LMDE = "LMDE";
        final String MNH = "MNH";
        final String MGEN = "MGEN";
        final String MMA = "MMA";
        final String CNAMTS = "CNAMTS";
        final String CCVRP = "CCVRP";
        final String MAS = "MAS";
        final String AG2R = "AG2R";
        final String MNFTC = "MNFTC";
        final String MGSP = "MGSP";
        final String salaire0 = "Mutuelle";
        Infox = "Mutuelle";
        Infoy = "Malades";
        text = "Nombre de malades par mutuelle";

        //                      / init
        dataset.addValue(getMaladeParMutuelle(1), salaire0, MAAF);
        dataset.addValue(getMaladeParMutuelle(2), salaire0, MNAM);
        dataset.addValue(getMaladeParMutuelle(3), salaire0, LMDE);
        dataset.addValue(getMaladeParMutuelle(4), salaire0, MNH);
        dataset.addValue(getMaladeParMutuelle(5), salaire0, MGEN);
        dataset.addValue(getMaladeParMutuelle(6), salaire0, MMA);
        dataset.addValue(getMaladeParMutuelle(7), salaire0, CNAMTS);
        dataset.addValue(getMaladeParMutuelle(8), salaire0, CCVRP);
        dataset.addValue(getMaladeParMutuelle(9), salaire0, MAS);
        dataset.addValue(getMaladeParMutuelle(10), salaire0, AG2R);
        dataset.addValue(getMaladeParMutuelle(11), salaire0, MNFTC);
        dataset.addValue(getMaladeParMutuelle(12), salaire0, MGSP);
        break;

    case 8:
        //set values
        final String malades = "Chambre";
        final String reas = "REA";
        final String chgs = "CHG";
        final String cars = "CAR";
        dataset.addValue(getChambreParService(1), malades, reas);
        dataset.addValue(getChambreParService(2), malades, chgs);
        dataset.addValue(getChambreParService(3), malades, cars);
        Infox = "Service";
        Infoy = "Nombre de chambre";
        text = "Nombre de chambre par service";
        break;

    default:
        break;

    }
    // Piechart
    if (action > 0 && action < 5) {
        final JFreeChart pieChart = ChartFactory.createPieChart(text, pieDataset, true, false, false);
        final ChartPanel cPanel = new ChartPanel(pieChart);
        reponse.add(cPanel);
        reponse.pack();
        //panelHistogramme.pack();
        reponse.setVisible(true);
    }
    //Histogramme
    if (action > 4 && action < 11) {

        final JFreeChart barChart = ChartFactory.createBarChart(text, Infox, Infoy, dataset,
                PlotOrientation.VERTICAL, true, true, false);
        final ChartPanel cPanel = new ChartPanel(barChart);
        reponse.add(cPanel);
        reponse.pack();
        //panelHistogramme.pack();
        reponse.setVisible(true);
    }

    /*
     DefaultPieDataset pieDataset = new DefaultPieDataset(); 
     pieDataset.setValue("Valeur1", new Integer(27)); 
     pieDataset.setValue("Valeur2", new Integer(10)); 
     pieDataset.setValue("Valeur3", new Integer(50)); 
     pieDataset.setValue("Valeur4", new Integer(5)); 
     JFreeChart pieChart = ChartFactory.createPieChart("Test camembert",pieDataset, true, true, true); 
     ChartPanel cPanel = new ChartPanel(pieChart); 
     panelHistogramme.add(cPanel); 
     */

}

From source file:pi.bestdeal.gui.InterfacePrincipale.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    int idd = (int) jTable3.getModel().getValueAt(jTable3.getSelectedRow(), 0);
    ChoixStat1 chStat = new ChoixStat1();
    ChoixStat2 chStat2 = new ChoixStat2();

    Object[] options = { "BACK", "NEXT" };
    int a = JOptionPane.showOptionDialog(null, chStat, "", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);
    int b = 0;//  w  w  w.  j  a  v a2s  .c  o m
    if (chStat.jRadiosexe.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 0;
    }
    if (chStat.jRadiosexe.isSelected() && chStat.jRadiores.isSelected()) {
        b = 1;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 2;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadiores.isSelected()) {
        b = 3;
    }
    if (a == 1 && b == 2) {
        chStat.setVisible(false);
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();

            XYSeriesCollection dataxy = charts.createDataset(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Consultations", //
                    dataxy, // Dataset
                    PlotOrientation.VERTICAL, // 

                    true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            JButton button = new JButton("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Chart d'volution des consultations",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        }
    }
    if (a == 1 && (b == 3)) {
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();
            //     JFreeChart chrt = ChartFactory.createXYStepAreaChart(null, null, null, null, PlotOrientation.HORIZONTAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled)
            XYSeriesCollection dataxy = charts.createDatasetRes(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Reservations",
                    dataxy, PlotOrientation.VERTICAL, true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            jpan.setLayout(new FlowLayout(FlowLayout.LEADING));
            JButton button = new JButton();

            button.setText("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Test", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE);
        }

    }
    if (a == 1 && b == 0) {
        ConsultationDAO cdao = ConsultationDAO.getInstance();
        DefaultPieDataset union = new DefaultPieDataset();
        union.setValue("Homme", cdao.consultationCounterByGender(false, idd));
        union.setValue("Femme", cdao.consultationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
    if (a == 1 && b == 1) {
        DefaultPieDataset union = new DefaultPieDataset();
        ReservationDAO dAO = ReservationDAO.getInstance();
        union.setValue("Homme", dAO.reservationCounterByGender(false, idd));
        union.setValue("Femme", dAO.reservationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "Chart de la rpartition des achat par sexe",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
}

From source file:GroupProject.OriginalChartUI.java

/**
 * The method to draw pie chart// w w w . ja  v a  2s  .c om
 * @param pieChartData the data used in the pie chart
 * @param pieTitle the measurement of pie chart
 */
public void drawPieChart(Map<String, Long> pieChartData, String pieTitle) {

    String title = pieTitle;
    ArrayList<String> keyArrayList = new ArrayList<>();
    ArrayList<Long> valueArrayList = new ArrayList<>();
    ArrayList<Color> colorArrayList = new ArrayList<>();

    colorArrayList.add(new Color(222, 235, 247));
    colorArrayList.add(new Color(109, 166, 217));
    colorArrayList.add(new Color(155, 195, 230));
    colorArrayList.add(new Color(126, 146, 222));
    colorArrayList.add(new Color(96, 158, 218));
    colorArrayList.add(new Color(53, 132, 203));
    colorArrayList.add(new Color(46, 116, 180));
    colorArrayList.add(new Color(31, 77, 119));

    DefaultPieDataset dataset = new DefaultPieDataset();
    Set set = pieChartData.keySet();
    for (Map.Entry<String, Long> data : pieChartData.entrySet()) {
        String key = data.getKey();
        Long value = data.getValue();
        keyArrayList.add(key);
        valueArrayList.add(value);
    }
    for (int i = 0; i < valueArrayList.size(); i++) {
        dataset.setValue(keyArrayList.get(i), valueArrayList.get(i));
    }
    JFreeChart chart = ChartFactory.createPieChart3D(title, dataset);
    chart.setBorderVisible(false);
    chart.setBorderPaint(new Color(255, 255, 255));
    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    for (int i = 0; i < valueArrayList.size(); i++) {
        Color color = colorArrayList.get(i);
        plot.setSectionPaint(keyArrayList.get(i), color);
    }
    plot.setOutlineVisible(false);
    plot.setForegroundAlpha(0.6f);
    plot.setStartAngle(0);
    plot.setBackgroundPaint(new java.awt.Color(255, 255, 255));
    ChartPanel chartPanel = new ChartPanel(chart);
    chartDisplayPanel.removeAll();
    chartDisplayPanel.add(chartPanel, BorderLayout.CENTER);
    chartDisplayPanel.validate();
}