Example usage for java.text NumberFormat getPercentInstance

List of usage examples for java.text NumberFormat getPercentInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getPercentInstance.

Prototype

public static final NumberFormat getPercentInstance() 

Source Link

Document

Returns a percentage format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:org.evosuite.statistics.backend.HTMLStatisticsBackend.java

/**
 * Write some overall stats//from ww w  .  j av a 2s .c  om
 * 
 * @param buffer
 *            a {@link java.lang.StringBuffer} object.
 * @param entry
 *            a {@link org.evosuite.utils.ReportGenerator.StatisticEntry}
 *            object.
 */
protected void writeResultTable(TestSuiteChromosome suite, StringBuffer buffer,
        Map<String, OutputVariable<?>> data) {

    //buffer.append("<h2>Statistics</h2>\n");
    buffer.append("<ul>\n");

    buffer.append("<li>");
    buffer.append(suite.getFitness());
    buffer.append(" fitness evaluations, ");
    buffer.append(suite.getAge());
    buffer.append(" generations, ");
    buffer.append(getOutputVariableValue(data, RuntimeVariable.Statements_Executed.name()));
    buffer.append(" statements, ");
    buffer.append(suite.size());
    buffer.append(" tests.\n");

    /*
    long duration_GA = (entry.end_time - entry.start_time) / 1000;
    long duration_MI = (entry.minimized_time - entry.end_time) / 1000;
    long duration_TO = (entry.minimized_time - entry.start_time) / 1000;
            
    buffer.append("<li>Time: "
      + String.format("%d:%02d:%02d", duration_TO / 3600,
                      (duration_TO % 3600) / 60, (duration_TO % 60)));
            
    buffer.append("(Search: "
      + String.format("%d:%02d:%02d", duration_GA / 3600,
                      (duration_GA % 3600) / 60, (duration_GA % 60)) + ", ");
    buffer.append("minimization: "
      + String.format("%d:%02d:%02d", duration_MI / 3600,
                      (duration_MI % 3600) / 60, (duration_MI % 60)) + ")\n");
    */

    buffer.append("<li>Covered " + getOutputVariableValue(data, RuntimeVariable.Covered_Branches.name()) + "/"
            + getOutputVariableValue(data, RuntimeVariable.Total_Branches.name()) + " branches, ");
    buffer.append("<li>Covered " + getOutputVariableValue(data, RuntimeVariable.Covered_Methods.name()) + "/"
            + getOutputVariableValue(data, RuntimeVariable.Total_Methods.name()) + " methods, ");
    buffer.append("<li>Covered " + getOutputVariableValue(data, RuntimeVariable.Covered_Goals.name()) + "/"
            + getOutputVariableValue(data, RuntimeVariable.Total_Goals.name()) + " total goals\n");
    if (data.containsKey(RuntimeVariable.MutationScore.name()))
        buffer.append("<li>Mutation score: " + NumberFormat.getPercentInstance()
                .format((Double) data.get(RuntimeVariable.MutationScore.name()).getValue()) + "\n");

    buffer.append("</ul>\n");
}

From source file:org.jspresso.framework.application.backend.AbstractBackendController.java

/**
 * Executes an action asynchronously, i.e. when
 * the action is annotated with {@link org.jspresso.framework.application.backend.action.Asynchronous}.
 *
 * @param action/*w  ww. j  av a 2  s .  co m*/
 *     the action to execute.
 * @param context
 *     the context
 * @return the slave thread executing the action.
 */
public AsyncActionExecutor executeAsynchronously(IAction action, Map<String, Object> context) {
    AbstractBackendController slaveBackendController = createBackendController();
    AsyncActionExecutor slaveExecutor = new AsyncActionExecutor(action, context,
            getControllerAsyncActionsThreadGroup(), slaveBackendController);
    asyncExecutors.add(slaveExecutor);
    Set<AsyncActionExecutor> oldRunningExecutors = new LinkedHashSet<>(getRunningExecutors());
    firePropertyChange("runningExecutors", oldRunningExecutors, getRunningExecutors());
    slaveExecutor.start();
    if (LOG.isDebugEnabled()) {
        LOG.debug("List of running executors :");
        for (AsyncActionExecutor executor : getRunningExecutors()) {
            LOG.debug("  --> Executor {} has completed {}", executor.getName(),
                    NumberFormat.getPercentInstance().format(executor.getProgress()));
        }
    }
    return slaveExecutor;
}

From source file:com.jd.survey.web.pdf.StatisticsPdf.java

private void writeOptionsQuestionStatistics(Document document, Question question,
        List<QuestionStatistic> questionStatistics, String optionLabel, String optionFrequencyLabel)
        throws Exception {

    NumberFormat percentFormat = NumberFormat.getPercentInstance();
    percentFormat.setMaximumFractionDigits(1);

    Table statsTable = createOptionsQuestionStatisticsTableHeader(optionLabel, optionFrequencyLabel);
    Cell cell;/*from   w w  w  .j  a v a2s.  co m*/

    int rowIndex = 0;
    for (QuestionOption option : question.getOptions()) {
        Boolean foundOption = false;
        cell = new Cell(new Paragraph(option.getText(), normalFont));
        //if ((rowIndex % 2) == 1) {cell.setBackgroundColor(new Color(244,244,244));}
        statsTable.addCell(cell);

        if (questionStatistics != null && questionStatistics.size() > 0) {
            for (QuestionStatistic questionStatistic : questionStatistics) {
                if (question.getType().getIsMultipleValue()) {
                    //multiple value question (checkboxes) match on order
                    if (questionStatistic.getOptionOrder().equals(option.getOrder())) {
                        foundOption = true;

                        cell = new Cell(new Paragraph(percentFormat.format(questionStatistic.getFrequency()),
                                normalFont));
                        statsTable.addCell(cell);

                        cell = new Cell();
                        Image img = Image.getInstance(this.getClass().getResource("/chartbar.png"));
                        cell.setColspan(5);
                        img.scaleAbsolute((float) (questionStatistic.getFrequency() * 210), 10f);
                        cell.addElement(img);
                        cell.setVerticalAlignment(Cell.ALIGN_BOTTOM);
                        statsTable.addCell(cell);
                        break;
                    }
                } else {
                    //single value question match on value
                    if (questionStatistic.getEntry() != null
                            && questionStatistic.getEntry().equals(option.getValue())) {
                        foundOption = true;
                        cell = new Cell(new Paragraph(percentFormat.format(questionStatistic.getFrequency()),
                                normalFont));
                        //if ((rowIndex % 2) == 1) {cell.setBackgroundColor(new Color(244,244,244));}
                        statsTable.addCell(cell);

                        cell = new Cell();
                        //if ((rowIndex % 2) == 1) {cell.setBackgroundColor(new Color(244,244,244));}
                        Image img = Image.getInstance(this.getClass().getResource("/chartbar.png"));
                        cell.setColspan(5);
                        img.scaleAbsolute((float) (questionStatistic.getFrequency() * 210), 10f);
                        cell.addElement(img);
                        cell.setVerticalAlignment(Cell.ALIGN_BOTTOM);
                        statsTable.addCell(cell);
                        break;
                    }

                }
            }
        }

        if (!foundOption) {

            cell = new Cell(new Paragraph(percentFormat.format(0), normalFont));
            //if ((rowIndex % 2) == 1) {cell.setBackgroundColor(new Color(244,244,244));}
            statsTable.addCell(cell);

            cell = new Cell();
            //if ((rowIndex % 2) == 1) {cell.setBackgroundColor(new Color(244,244,244));}
            cell.setColspan(5);
            statsTable.addCell(cell);
        }
        rowIndex++;
    }
    document.add(statsTable);

}

From source file:KIDLYFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The colour of each section will be determined by the move from the value
 * for the same key in <code>previousDataset</code>. ie if value1 > value2
 * then the section will be in green (unless <code>greenForIncrease</code>
 * is <code>false</code>, in which case it would be <code>red</code>).
 * Each section can have a shade of red or green as the difference can be
 * tailored between 0% (black) and percentDiffForMaxScale% (bright
 * red/green)./*  w  w  w . ja va2s .  co  m*/
 * <p>
 * For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a
 * difference of 5% will have a half shade of red/green, a difference of
 * 10% or more will have a maximum shade/brightness of red/green.
 * <P>
 * The chart object returned by this method uses a {@link PiePlot} instance
 * as the plot.
 * <p>
 * Written by <a href="mailto:opensource@objectlab.co.uk">Benoit
 * Xhenseval</a>.
 *
 * @param title  the chart title (<code>null</code> permitted).
 * @param dataset  the dataset for the chart (<code>null</code> permitted).
 * @param previousDataset  the dataset for the last run, this will be used
 *                         to compare each key in the dataset
 * @param percentDiffForMaxScale scale goes from bright red/green to black,
 *                               percentDiffForMaxScale indicate the change
 *                               required to reach top scale.
 * @param greenForIncrease  an increase since previousDataset will be
 *                          displayed in green (decrease red) if true.
 * @param legend  a flag specifying whether or not a legend is required.
 * @param tooltips  configure chart to generate tool tips?
 * @param locale  the locale (<code>null</code> not permitted).
 * @param subTitle displays a subtitle with colour scheme if true
 * @param showDifference  create a new dataset that will show the %
 *                        difference between the two datasets.
 *
 * @return A pie chart.
 *
 * @since 1.0.7
 */
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, Locale locale,
        boolean subTitle, boolean showDifference) {

    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));
    }

    List keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Comparable key = (Comparable) it.next();
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.green);
            } else {
                plot.setSectionPaint(key, Color.red);
            }
            if (showDifference) {
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    if (subTitle) {
        TextTitle subtitle = null;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }
    currentTheme.apply(chart);
    return chart;
}

From source file:com.safi.workshop.serverview.ServerViewPanel.java

public static void main(String[] args) {
    String s = String.format(DRIVE_SPACE_LABEL_FORMAT, "44.1 MB", "45.3 MB");
    System.err.println(s);/*w w w.j  a  va  2s  .  c  o m*/
    s = NumberFormat.getPercentInstance().format(.4433d);
    System.err.println(String.format("CPU Usage %1$-4s", s));
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.StackedBar.java

/**
 * Inherited by IChart.//from ww  w .  j av  a  2s .  c o m
 * 
 * @param chartTitle the chart title
 * @param dataset the dataset
 * 
 * @return the j free chart
 */

public JFreeChart createChart(DatasetMap datasets) {

    logger.debug("IN");
    CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1");

    logger.debug("Taken Dataset");

    logger.debug("Get plot orientaton");
    PlotOrientation plotOrientation = PlotOrientation.VERTICAL;
    if (horizontalView) {
        plotOrientation = PlotOrientation.HORIZONTAL;
    }

    logger.debug("Call Chart Creation");
    JFreeChart chart = ChartFactory.createStackedBarChart(name, // chart title
            categoryLabel, // domain axis label
            valueLabel, // range axis label
            dataset, // data
            plotOrientation, // the plot orientation
            false, // legend
            true, // tooltips
            false // urls
    );
    logger.debug("Chart Created");

    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(color);
    plot.setRangeGridlinePaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);

    logger.debug("set renderer");
    StackedBarRenderer renderer = (StackedBarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setBaseItemLabelsVisible(true);

    if (percentageValue)
        renderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("#,##.#%")));
    else if (makePercentage)
        renderer.setRenderAsPercentages(true);

    /*
    else
       renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
     */
    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

    if (maxBarWidth != null) {
        renderer.setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    boolean document_composition = false;
    if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
        document_composition = true;

    logger.debug("Calling Url Generation");

    MyCategoryUrlGenerator mycatUrl = null;
    if (rootUrl != null) {
        logger.debug("Set MycatUrl");
        mycatUrl = new MyCategoryUrlGenerator(rootUrl);

        mycatUrl.setDocument_composition(document_composition);
        mycatUrl.setCategoryUrlLabel(categoryUrlName);
        mycatUrl.setSerieUrlLabel(serieUrlname);
    }
    if (mycatUrl != null)
        renderer.setItemURLGenerator(mycatUrl);

    logger.debug("Text Title");

    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }

    logger.debug("Style Labels");

    Color colorSubInvisibleTitle = Color.decode("#FFFFFF");
    StyleLabel styleSubSubTitle = new StyleLabel("Arial", 12, colorSubInvisibleTitle);
    TextTitle subsubTitle = setStyleTitle("", styleSubSubTitle);
    chart.addSubtitle(subsubTitle);
    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    chart.setBackgroundPaint(color);

    logger.debug("Axis creation");
    // set the range axis to display integers only...

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    if (makePercentage)
        rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    else
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setNumberFormatOverride(nf);

    if (rangeAxisLocation != null) {
        if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);
        } else if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
        }
    }

    renderer.setDrawBarOutline(false);

    logger.debug("Set series color");

    int seriesN = dataset.getRowCount();
    if (orderColorVector != null && orderColorVector.size() > 0) {
        logger.debug("color serie by SERIES_ORDER_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            if (orderColorVector.get(i) != null) {
                Color color = orderColorVector.get(i);
                renderer.setSeriesPaint(i, color);
            }
        }
    } else if (colorMap != null) {
        for (int i = 0; i < seriesN; i++) {
            String serieName = (String) dataset.getRowKey(i);

            // if serie has been rinominated I must search with the new name!
            String nameToSearchWith = (seriesLabelsMap != null && seriesLabelsMap.containsKey(serieName))
                    ? seriesLabelsMap.get(serieName).toString()
                    : serieName;

            Color color = (Color) colorMap.get(nameToSearchWith);
            if (color != null) {
                renderer.setSeriesPaint(i, color);
                renderer.setSeriesItemLabelFont(i,
                        new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            }
        }
    }

    logger.debug("If cumulative set series paint " + cumulative);

    if (cumulative) {
        int row = dataset.getRowIndex("CUMULATIVE");
        if (row != -1) {
            if (color != null)
                renderer.setSeriesPaint(row, color);
            else
                renderer.setSeriesPaint(row, Color.WHITE);
        }
    }

    MyStandardCategoryItemLabelGenerator generator = null;
    logger.debug("Are there addition labels " + additionalLabels);
    logger.debug("Are there value labels " + showValueLabels);

    if (showValueLabels) {
        renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        if (valueLabelsPosition.equalsIgnoreCase("inside")) {
            renderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
            renderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
        } else {
            renderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
            renderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
        }
    } else if (additionalLabels) {

        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());
        logger.debug("generator set");

        double orient = (-Math.PI / 2.0);
        logger.debug("add labels style");
        if (styleValueLabels.getOrientation() != null
                && styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
            orient = 0.0;
        }
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        logger.debug("add labels style set");

        renderer.setBaseItemLabelGenerator(generator);
        renderer.setBaseItemLabelsVisible(true);
        //vertical labels          
        renderer.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        renderer.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));

        logger.debug("end of add labels ");

    }

    logger.debug("domain axis");

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4.0));
    domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setLabelPaint(styleYaxesLabels.getColor());
    domainAxis
            .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());
    //opacizzazione colori
    if (!cumulative)
        plot.setForegroundAlpha(0.6f);
    if (legend == true)
        drawLegend(chart);

    logger.debug("OUT");
    return chart;

}

From source file:com.android.launcher3.BubbleTextView.java

public void applyState(boolean promiseStateChanged) {
    if (getTag() instanceof ShortcutInfo) {
        ShortcutInfo info = (ShortcutInfo) getTag();
        final boolean isPromise = info.isPromise();
        final int progressLevel = isPromise
                ? ((info.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE) ? info.getInstallProgress()
                        : 0))//from  w  ww  .  jav a2 s  .c  o m
                : 100;

        setContentDescription(progressLevel > 0
                ? getContext().getString(R.string.app_downloading_title, info.title,
                        NumberFormat.getPercentInstance().format(progressLevel * 0.01))
                : getContext().getString(R.string.app_waiting_download_title, info.title));

        if (mIcon != null) {
            final PreloadIconDrawable preloadDrawable;
            if (mIcon instanceof PreloadIconDrawable) {
                preloadDrawable = (PreloadIconDrawable) mIcon;
            } else {
                preloadDrawable = new PreloadIconDrawable(mIcon, getPreloaderTheme());
                setIcon(preloadDrawable);
            }

            preloadDrawable.setLevel(progressLevel);
            if (promiseStateChanged) {
                preloadDrawable.maybePerformFinishedAnimation();
            }
        }
    }
}

From source file:edu.dlnu.liuwenpeng.ChartFactory.ChartFactory.java

/**    
* Creates a pie chart with default settings that compares 2 datasets.      
* The colour of each section will be determined by the move from the value    
* for the same key in <code>previousDataset</code>. ie if value1 > value2     
* then the section will be in green (unless <code>greenForIncrease</code>     
* is <code>false</code>, in which case it would be <code>red</code>).      
* Each section can have a shade of red or green as the difference can be     
* tailored between 0% (black) and percentDiffForMaxScale% (bright     
* red/green).    //from w ww  . j  a v  a2s. c  o  m
* <p>    
* For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a     
* difference of 5% will have a half shade of red/green, a difference of     
* 10% or more will have a maximum shade/brightness of red/green.    
* <P>    
* The chart object returned by this method uses a {@link PiePlot} instance    
* as the plot.    
* <p>    
* Written by <a href="mailto:opensource@objectlab.co.uk">Benoit     
* Xhenseval</a>.    
*    
* @param title  the chart title (<code>null</code> permitted).    
* @param dataset  the dataset for the chart (<code>null</code> permitted).    
* @param previousDataset  the dataset for the last run, this will be used     
*                         to compare each key in the dataset    
* @param percentDiffForMaxScale scale goes from bright red/green to black,    
*                               percentDiffForMaxScale indicate the change     
*                               required to reach top scale.    
* @param greenForIncrease  an increase since previousDataset will be     
*                          displayed in green (decrease red) if true.    
* @param legend  a flag specifying whether or not a legend is required.    
* @param tooltips  configure chart to generate tool tips?    
* @param urls  configure chart to generate URLs?    
* @param subTitle displays a subtitle with colour scheme if true    
* @param showDifference  create a new dataset that will show the %     
*                        difference between the two datasets.     
*    
* @return A pie chart.    
*/
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, boolean urls,
        boolean subTitle, boolean showDifference) {

    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator());
    }
    if (urls) {
        plot.setURLGenerator(new StandardPieURLGenerator());
    }

    List keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Comparable key = (Comparable) it.next();
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.green);
            } else {
                plot.setSectionPaint(key, Color.red);
            }
            if (showDifference) {
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    if (subTitle) {
        TextTitle subtitle = null;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }

    return chart;
}

From source file:com.jd.survey.web.pdf.StatisticsPdf.java

private void writeBooleanMatrixQuestionStatistics(Document document, Question question,
        List<QuestionStatistic> questionStatistics, String trueLabel, String falseLabel) throws Exception {

    NumberFormat percentFormat = NumberFormat.getPercentInstance();
    percentFormat.setMaximumFractionDigits(1);

    Table statsTable;//  w ww . ja v  a 2  s  .c  om
    Cell cell;

    statsTable = new Table(question.getColumnLabels().size() + 1);
    statsTable.setWidth(94);
    statsTable.setBorder(0);
    statsTable.setOffset(5);
    statsTable.setPadding(2);
    statsTable.setDefaultCellBorder(0);

    //header
    cell = new Cell();
    cell.setBorder(Cell.BOTTOM);
    statsTable.addCell(cell);
    for (QuestionColumnLabel columnLabel : question.getColumnLabels()) {
        cell = new Cell(new Paragraph(columnLabel.getLabel(), boldedFont));
        cell.setBorder(Cell.BOTTOM);
        statsTable.addCell(cell);
    }
    int rowIndex = 1;
    for (QuestionRowLabel rowLabel : question.getRowLabels()) {
        cell = new Cell(new Paragraph(rowLabel.getLabel(), boldedFont));
        cell.setBorder(Cell.RIGHT);
        if ((rowIndex % 2) == 1) {
            cell.setBackgroundColor(new Color(244, 244, 244));
        }
        statsTable.addCell(cell);
        for (QuestionColumnLabel columnLabel : question.getColumnLabels()) {
            boolean found = false;
            cell = new Cell();
            if ((rowIndex % 2) == 1) {
                cell.setBackgroundColor(new Color(244, 244, 244));
            }
            for (QuestionStatistic questionStatistic : questionStatistics) {
                if (questionStatistic.getRowOrder().equals(rowLabel.getOrder())
                        && questionStatistic.getColumnOrder().equals(columnLabel.getOrder())
                        && questionStatistic.getEntry().equals("1")) {
                    cell.add(new Paragraph(
                            trueLabel + ": " + percentFormat.format(questionStatistic.getFrequency()),
                            normalFont));
                    found = true;
                    break;
                }
            }
            if (!found) {
                cell.add(new Paragraph(trueLabel + ": " + percentFormat.format(0), normalFont));
            }

            found = false;
            for (QuestionStatistic questionStatistic : questionStatistics) {
                if (questionStatistic.getRowOrder().equals(rowLabel.getOrder())
                        && questionStatistic.getColumnOrder().equals(columnLabel.getOrder())
                        && questionStatistic.getEntry().equals("0")) {
                    cell.add(new Paragraph(
                            falseLabel + ": " + percentFormat.format(questionStatistic.getFrequency()),
                            normalFont));
                    found = true;
                    break;
                }
            }
            if (!found) {
                cell.add(new Paragraph(falseLabel + ": " + percentFormat.format(0), normalFont));
            }

            statsTable.addCell(cell);
        }
        rowIndex++;
    }

    document.add(statsTable);

}

From source file:com.limewoodmedia.nsdroid.activities.Nation.java

private void doPeopleSetup() {
    // Chart/*from   www . jav a 2  s.  com*/
    peopleSeries.clear();
    peopleRenderer.removeAllRenderers();
    Set<Map.Entry<CauseOfDeath, Float>> deaths = data.deaths.entrySet();
    NumberFormat format = NumberFormat.getPercentInstance();
    format.setMaximumFractionDigits(1);
    Map<CauseOfDeath, String> legends = new HashMap<CauseOfDeath, String>();
    StringBuilder legend;
    String desc;
    int colour;
    for (Map.Entry<CauseOfDeath, Float> d : deaths) {
        desc = d.getKey() == CauseOfDeath.ANIMAL_ATTACK
                ? d.getKey().getDescription().replace("Animal",
                        data.animal.substring(0, 1).toUpperCase() + data.animal.substring(1))
                : d.getKey().getDescription();
        peopleSeries.add(desc, d.getValue() / 100f);
        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
        colour = CHART_COLOURS[(peopleSeries.getItemCount() - 1) % CHART_COLOURS.length];
        renderer.setColor(colour);
        renderer.setChartValuesFormat(format);
        peopleRenderer.addSeriesRenderer(renderer);
        legend = new StringBuilder();
        legend.append("<b><font color='").append(Integer.toString(colour)).append("'>").append(desc);
        legends.put(d.getKey(), legend.toString());
    }
    peopleChart.repaint();

    // Legend
    legend = new StringBuilder();
    for (CauseOfDeath cod : CauseOfDeath.values()) {
        if (legend.length() > 0) {
            legend.append("<br/>");
        }
        if (legends.containsKey(cod)) {
            legend.append(legends.get(cod)).append(": ").append(Float.toString(data.deaths.get(cod)))
                    .append("%</font></b>");
        } else {
            legend.append("<font color='grey'>").append(cod.getDescription()).append(": ").append("0%</font>");
        }
    }
    peopleLegend.setText(Html.fromHtml(legend.toString()), TextView.BufferType.SPANNABLE);
}