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:be.hogent.tarsos.util.histogram.Histogram.java

/**
 * Returns a string representation of the histogram.
 * <p>//from  www  .j av a 2s .co  m
 * Uses code from <a href="http://commons.apache.org/math">Apache Commons
 * Math"</a> licensed to the Apache Software Foundation (ASF) under one or
 * more contributor license agreements.
 * </p>
 * 
 * @param asciiArt
 *            If true it generates an ascii representation of a histogram,
 *            otherwise it generates a frequency table
 * @return a string representation.
 */
public String toString(final boolean asciiArt) {
    if (asciiArt) {
        final StringBuffer outBuffer = new StringBuffer();
        outBuffer.append('\n');
        final Iterator<Double> iter = freqTable.keySet().iterator();
        while (iter.hasNext()) {
            final Double value = iter.next();
            outBuffer.append(value).append("\t\t|");
            for (int i = 0; i < getPct(value) * 100; i++) {
                outBuffer.append('x');
            }
            outBuffer.append('\n');
        }
        outBuffer.append('\n');
        return outBuffer.toString();
    } else {
        final NumberFormat nf = NumberFormat.getPercentInstance();
        final StringBuffer outBuffer = new StringBuffer();
        outBuffer.append("\nValue \t Freq. \t Pct. \t Cum Pct. \n");
        final Iterator<Double> iter = freqTable.keySet().iterator();
        while (iter.hasNext()) {
            final Double value = iter.next();
            outBuffer.append(value);
            outBuffer.append('\t');
            outBuffer.append(getCount(value));
            outBuffer.append('\t');
            outBuffer.append(nf.format(getPct(value)));
            outBuffer.append('\t');
            outBuffer.append(nf.format(getCumPct(value)));
            outBuffer.append('\n');
        }
        return outBuffer.toString();
    }
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private void renderChartInfo() {
    HashMap<Object, Marker> marks = new HashMap<>();
    DefaultPieDataset dataset = buildDataset(marks);

    JFreeChart chart = ChartFactory.createPieChart(null, // chart title
            dataset, // data
            true, // include legend
            true, false);/*w  w  w. jav a  2s  .  c o  m*/
    chart.setBackgroundPaint(null);
    //chart.setBorderStroke(null);
    chart.setBorderVisible(false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    // plot.setBackgroundPaint(null);
    //  plot.setShadowPaint(null);

    for (Object o : marks.keySet()) {
        if (iCurrentView == ID_ALLY_CHART) {
            Ally a = (Ally) o;
            plot.setSectionPaint(a.getTag(), marks.get(a).getMarkerColor());
        } else {
            Tribe t = (Tribe) o;
            plot.setSectionPaint(t.getName(), marks.get(t).getMarkerColor());
        }
    }
    //plot.setCircular(true);
    //  plot.setMaximumLabelWidth(30.0);
    /*
        * plot.setLabelGenerator(new StandardPieSectionLabelGenerator( "{0} = {2}", NumberFormat.getNumberInstance(),
        * NumberFormat.getPercentInstance()));
        */
    //   chart.getLegend().setVerticalAlignment(VerticalAlignment.CENTER);
    //  chart.getLegend().setPosition(RectangleEdge.RIGHT);
    // plot.setMaximumLabelWidth(20.0);
    plot.setLabelGenerator(null);
    plot.setBackgroundPaint(Constants.DS_BACK);
    /*
     * plot.setInteriorGap(0.0); plot.setLabelGap(0.0);
     */
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {2}",
            NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

    /*
     * plot.getL plot.setLabelFont(g2d.getFont().deriveFont(10.0f));
     */

    //plot.setLabelGenerator(null);

    //plot.setMaximumLabelWidth(30.0);
    //plot.getLabelDistributor().distributeLabels(10.0, 20.0);
    //chart.draw(g2d, new Rectangle2D.Float(20, 20, 100, 100));

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    plot.setOutlineVisible(false);
    mChartImage = chart.createBufferedImage(getWidth(), getHeight());
    //chart.draw(g2d, new Rectangle2D.Float(50, 50, 400, 400));
    //g2d.drawImage(bi, 30, 30, null);

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

    //bi = chart.createBufferedImage(240, 240);
    // g2d.drawImage(bi, 30, 30, null);
}

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)./*from   ww  w  .  java  2s .  com*/
 * <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);
    }
    currentTheme.apply(chart);
    return chart;
}

From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java

protected void createColumns() {

    final TableViewerColumn name = new TableViewerColumn(viewer, SWT.LEFT);
    name.getColumn().setText("Name");
    name.getColumn().setWidth(260);/*from  w ww  .ja va2  s . c  o m*/
    name.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            return ((StatusBean) element).getName();
        }
    });

    final TableViewerColumn status = new TableViewerColumn(viewer, SWT.LEFT);
    status.getColumn().setText("Status");
    status.getColumn().setWidth(140);
    status.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            return ((StatusBean) element).getStatus().toString();
        }
    });

    final TableViewerColumn pc = new TableViewerColumn(viewer, SWT.CENTER);
    pc.getColumn().setText("Complete (%)");
    pc.getColumn().setWidth(120);
    pc.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            try {
                return NumberFormat.getPercentInstance()
                        .format(((StatusBean) element).getPercentComplete() / 100d);
            } catch (Exception ne) {
                return "-";
            }
        }
    });

    final TableViewerColumn submittedDate = new TableViewerColumn(viewer, SWT.CENTER);
    submittedDate.getColumn().setText("Date Submitted");
    submittedDate.getColumn().setWidth(150);
    submittedDate.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            try {
                return DateFormat.getDateTimeInstance()
                        .format(new Date(((StatusBean) element).getSubmissionTime()));
            } catch (Exception e) {
                return e.getMessage();
            }
        }
    });

    final TableViewerColumn message = new TableViewerColumn(viewer, SWT.LEFT);
    message.getColumn().setText("Message");
    message.getColumn().setWidth(150);
    message.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            try {
                return ((StatusBean) element).getMessage();
            } catch (Exception e) {
                return e.getMessage();
            }
        }
    });

    final TableViewerColumn location = new TableViewerColumn(viewer, SWT.LEFT);
    location.getColumn().setText("Location");
    location.getColumn().setWidth(300);
    location.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            try {
                final StatusBean bean = (StatusBean) element;
                return bean.getRunDirectory();
            } catch (Exception e) {
                return e.getMessage();
            }
        }

        public Color getForeground(Object element) {
            return getSite().getShell().getDisplay().getSystemColor(SWT.COLOR_BLUE);
        }
    });

    final TableViewerColumn host = new TableViewerColumn(viewer, SWT.CENTER);
    host.getColumn().setText("Host");
    host.getColumn().setWidth(150);
    host.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            try {
                return ((StatusBean) element).getHostName();
            } catch (Exception e) {
                return e.getMessage();
            }
        }
    });

    final TableViewerColumn user = new TableViewerColumn(viewer, SWT.CENTER);
    user.getColumn().setText("User Name");
    user.getColumn().setWidth(150);
    user.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            try {
                return ((StatusBean) element).getUserName();
            } catch (Exception e) {
                return e.getMessage();
            }
        }
    });

    MouseMoveListener cursorListener = new MouseMoveListener() {
        @Override
        public void mouseMove(MouseEvent e) {
            Point pt = new Point(e.x, e.y);
            TableItem item = viewer.getTable().getItem(pt);
            if (item == null) {
                viewer.getTable().setCursor(null);
                return;
            }
            Rectangle rect = item.getBounds(5);
            if (rect.contains(pt)) {
                viewer.getTable().setCursor(Display.getDefault().getSystemCursor(SWT.CURSOR_HAND));
            } else {
                viewer.getTable().setCursor(null);
            }

        }
    };
    viewer.getTable().addMouseMoveListener(cursorListener);

    MouseAdapter mouseClick = new MouseAdapter() {
        @Override
        public void mouseDown(MouseEvent e) {
            Point pt = new Point(e.x, e.y);
            TableItem item = viewer.getTable().getItem(pt);
            if (item == null)
                return;
            Rectangle rect = item.getBounds(5);
            if (rect.contains(pt)) {

                final StatusBean bean = (StatusBean) item.getData();
                openResults(bean);
            }
        }
    };

    viewer.getTable().addMouseListener(mouseClick);

}

From source file:org.jfree.chart.ChartFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The color of each section will be determined by the move from the value
 * for the same key in {@code previousDataset}. ie if value1 &gt; value2
 * then the section will be in green (unless {@code greenForIncrease}
 * is {@code false}, in which case it would be {@code red}).
 * 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.  ja  va 2  s .  c om
 * <p>
 * For instance if {@code percentDiffForMaxScale} 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} permitted).
 * @param dataset  the dataset for the chart ({@code null} 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 locale  the locale ({@code null} not permitted).
 * @param subTitle displays a subtitle with color 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, 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));

    plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));

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

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Comparable key : keys) {
        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) {
                assert series != null; // suppress compiler warning
                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) {
                assert series != null; // suppress compiler warning
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

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

    JFreeChart chart = new JFreeChart(title, plot);

    if (subTitle) {
        TextTitle 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.jd.survey.web.pdf.StatisticsPdf.java

private void writeNumericMatrixQuestionStatistics(Document document, Question question,
        List<QuestionStatistic> questionStatistics, String minimumLabel, String maximumLabel,
        String averageLabel, String standardDeviationLabel) throws Exception {

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

    Table statsTable;/*from w  w  w  . j ava 2 s . c  o  m*/
    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())) {
                    cell.add(new Paragraph(
                            minimumLabel + ": " + BigDecimalValidator.getInstance()
                                    .format(questionStatistic.getMin(), LocaleContextHolder.getLocale()),
                            normalFont));
                    cell.add(new Paragraph(
                            maximumLabel + ": " + BigDecimalValidator.getInstance()
                                    .format(questionStatistic.getMax(), LocaleContextHolder.getLocale()),
                            normalFont));
                    cell.add(new Paragraph(
                            averageLabel + ": " + BigDecimalValidator.getInstance()
                                    .format(questionStatistic.getAverage(), LocaleContextHolder.getLocale()),
                            normalFont));
                    cell.add(new Paragraph(standardDeviationLabel + ": "
                            + BigDecimalValidator.getInstance().format(
                                    questionStatistic.getSampleStandardDeviation(),
                                    LocaleContextHolder.getLocale()),
                            normalFont));

                    break;
                }
            }
            if (!found) {
            }

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

    document.add(statsTable);

}

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

private void doGovernmentSetup() {
    governmentTitle.setText(getString(R.string.nation_government_title, Utils.capitalize(data.demonym)));
    // Government size and percent
    double gov = 0;
    if (data.sectors.containsKey(IndustrySector.GOVERNMENT)) {
        gov = data.sectors.get(IndustrySector.GOVERNMENT);
    }/*  w ww. j  a va 2  s.  c  o m*/
    governmentSize.setText(getString(R.string.nation_government_size,
            Utils.formatCurrencyAmount(this, Math.round(data.gdp * (gov / 100d))), data.currency));
    governmentPercent.setText(getString(R.string.nation_government_percent, String.format("%.1f", gov)));
    governmentSeries.clear();
    governmentRenderer.removeAllRenderers();
    Set<Map.Entry<Department, Float>> depts = data.governmentBudget.entrySet();
    TreeSet<Map.Entry<IDescriptable, Float>> departments = new TreeSet<>();
    for (Map.Entry<Department, Float> d : depts) {
        departments.add(new DescriptionMapEntry(d));
    }
    NumberFormat format = NumberFormat.getPercentInstance();
    format.setMaximumFractionDigits(1);
    Map<IDescriptable, String> legends = new HashMap<>();
    StringBuilder legend;
    String desc;
    int colour;
    for (Map.Entry<IDescriptable, Float> d : departments) {
        if (d.getValue() == 0)
            continue;
        desc = d.getKey().getDescription();
        governmentSeries.add(desc, d.getValue() / 100f);
        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
        colour = CHART_COLOURS[(governmentSeries.getItemCount() - 1) % CHART_COLOURS.length];
        renderer.setColor(colour);
        renderer.setChartValuesFormat(format);
        governmentRenderer.addSeriesRenderer(renderer);
        legend = new StringBuilder();
        legend.append("<b><font color='").append(Integer.toString(colour)).append("'>").append(desc);
        legends.put(d.getKey(), legend.toString());
    }
    governmentChart.repaint();

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

From source file:org.talend.dataprofiler.chart.util.TopChartFactory.java

/**
 * DOC xqliu Comment method "createStackedBarChart".
 * //from w ww.j a  v  a 2 s .  co m
 * @param title
 * @param domainAxisLabel
 * @param rangeAxisLabel
 * @param dataset
 * @param orientation
 * @param legend
 * @param tooltips
 * @param urls
 * @return
 */
public static JFreeChart createStackedBarChart(String title, String domainAxisLabel, String rangeAxisLabel,
        CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) {
    // ADD msjian TDQ-5112 2012-4-10: after upgrate to jfreechart-1.0.12.jar, change the default chart wallPaint
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    // TDQ-5112~
    final JFreeChart chart = ChartFactory.createStackedBarChart(title, domainAxisLabel, rangeAxisLabel, dataset,
            orientation, legend, tooltips, urls);

    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setRangeGridlinesVisible(true);

    StackedBarRenderer sbr = (StackedBarRenderer) plot.getRenderer();
    sbr.setBaseItemLabelsVisible(true);
    sbr.setRenderAsPercentages(true);
    sbr.setBaseItemLabelGenerator(new DQRuleItemLabelGenerator("{3}", NumberFormat.getIntegerInstance())); //$NON-NLS-1$
    sbr.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
    // ADD xqliu 2010-03-10 feature 10834
    // sbr.setBaseToolTipGenerator(new DQRuleToolTipGenerator(ChartDecorator.NEW_TOOL_TIP_FORMAT_STRING,
    // NumberFormat
    // .getInstance()));
    // ~10834

    // ADD TDQ-5251 msjian 2012-7-31: do not display the shadow
    sbr.setShadowVisible(false);
    // TDQ-5251~

    NumberAxis axis = (NumberAxis) plot.getRangeAxis();
    axis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    axis.setUpperMargin(0.05f);
    axis.setLowerMargin(0.01f);

    return chart;
}

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

public void update(SysInfo info) {
    if (isDisposed() || info == null || currentInfo == info || info.equals(currentInfo))
        return;/*  w ww  .  j  a va  2  s .  com*/
    this.currentInfo = info;

    final double totalMemInMegs = info.getTotalMemory() / BYTES_PER_MEGABYTE;
    memoryBar.setMaximum((int) totalMemInMegs);
    memoryBar.setSelection((int) (totalMemInMegs - (info.getFreeMemory() / BYTES_PER_MEGABYTE)));
    String totalString = StorageUnit.of(info.getTotalMemory()).format(info.getTotalMemory());
    String memString = StorageUnit.of(info.getTotalMemory() - info.getFreeMemory())
            .format(info.getTotalMemory() - info.getFreeMemory());
    final String totMemString = String.format(SEVER_MEMORY_LABEL_FORMAT, memString, totalString);
    serverMemoryLabel.setText(totMemString);
    serverMemoryLabel.pack();

    double totalDriveSpace = info.getTotalSpace() / BYTES_PER_MEGABYTE;
    driveSpaceBar.setMaximum((int) totalDriveSpace);
    driveSpaceBar.setSelection((int) (info.getFreeSpace() / BYTES_PER_MEGABYTE));

    String totalSpace = StorageUnit.of(info.getTotalSpace()).format(info.getTotalSpace());
    String usedSpace = StorageUnit.of(info.getTotalSpace() - info.getFreeSpace())
            .format(info.getTotalSpace() - info.getFreeSpace());
    driveSpaceLabel.setText(String.format(DRIVE_SPACE_LABEL_FORMAT, usedSpace, totalSpace));
    driveSpaceLabel.pack();

    cpuUsageBar.setMaximum(100);
    cpuUsageBar.setSelection((int) Math.floor(info.getCPUUsage() * 100d));
    cpuUsageLabel.setText(String.format("CPU Usage %1$-4s",
            info.getCPUUsage() == -1d ? "NA" : NumberFormat.getPercentInstance().format(info.getCPUUsage())));
    cpuUsageLabel.pack();

    ipAddressLabel.setText(info.getIPAddress());
    ipAddressLabel.pack();

    macAddressLabel.setText(info.getMacAddress());
    macAddressLabel.pack();

    incomingCallsLabel.setText(String.valueOf(info.getIncomingCalls()));
    incomingCallsLabel.pack();

    custInitiationsLabel.setText(String.valueOf(info.getCustomInitiations()));
    custInitiationsLabel.pack();

    int days = (int) (info.getUptime() / MILLIS_PER_DAY);
    int hours = (int) ((info.getUptime() - days * MILLIS_PER_DAY) / MILLIS_PER_HOUR);
    int minutes = (int) ((info.getUptime() - (days * MILLIS_PER_DAY + hours * MILLIS_PER_HOUR))
            / MILLIS_PER_MINUTE);
    StringBuffer buf = new StringBuffer();
    boolean hadPrev = false;
    if (days > 0) {
        buf.append(days).append(days > 1 ? " Days" : " Day");
        hadPrev = true;
    }

    if (hours > 0) {
        if (hadPrev)
            buf.append(",");
        buf.append(hours).append(hours > 1 ? " Hours" : " Hour");
        hadPrev = true;
    }

    if (minutes > 0) {
        if (hadPrev)
            buf.append(",");
        buf.append(minutes).append(minutes > 1 ? " Minutes" : " Minute");
    }

    uptimeLabel.setText(buf.toString());
    uptimeLabel.pack();

    final Calendar instance = Calendar.getInstance();
    instance.setTimeInMillis(System.currentTimeMillis() - info.getUptime());
    lastRebootLabel.pack();

    label_1.setText(info.getServerID() == null ? "" : info.getServerID());
    label_1.pack();

    this.safiServerVersionLabel.setText(info.getSafiServerVersion() == null ? "" : info.getSafiServerVersion());
    this.safiserverHeaderVersionLabel
            .setText(info.getSafiServerVersion() == null ? "" : info.getSafiServerVersion());

    safiserverHeaderVersionLabel.pack();
    safiServerVersionLabel.pack();
}

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

private void doEconomySetup() {
    economyTitle.setText(getString(R.string.nation_economy_title, Utils.capitalize(data.demonym)));
    // GDP, GDPPC, Poorest and Richest
    economyGDP.setText(/*  w  w  w  .  j av a 2 s. c  om*/
            getString(R.string.nation_economy_gdp, Utils.formatCurrencyAmount(this, data.gdp), data.currency));
    economyGDPPC.setText(getString(R.string.nation_economy_gdppc,
            Utils.formatCurrencyAmount(this, Math.round(data.gdp / (data.population * 1000000f))),
            data.currency));
    economyPoorest.setText(getString(R.string.nation_economy_poorest,
            Utils.formatCurrencyAmount(this, data.poorest), data.currency));
    economyRichest.setText(getString(R.string.nation_economy_richest,
            Utils.formatCurrencyAmount(this, data.richest), data.currency));

    economySeries.clear();
    economyRenderer.removeAllRenderers();
    Set<Map.Entry<IndustrySector, Float>> secs = data.sectors.entrySet();
    TreeSet<Map.Entry<IDescriptable, Float>> sectors = new TreeSet<>();
    for (Map.Entry<IndustrySector, Float> d : secs) {
        sectors.add(new DescriptionMapEntry(d, false));
    }
    NumberFormat format = NumberFormat.getPercentInstance();
    format.setMaximumFractionDigits(1);

    Map<IDescriptable, String> legends = new HashMap<>();
    StringBuilder legend;
    String desc;
    int colour;
    for (Map.Entry<IDescriptable, Float> s : sectors) {
        if (s.getValue() == 0)
            continue;
        desc = s.getKey().getDescription();
        economySeries.add(desc, s.getValue() / 100f);
        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
        colour = CHART_COLOURS[(economySeries.getItemCount() - 1) % CHART_COLOURS.length];
        renderer.setColor(colour);
        renderer.setChartValuesFormat(format);
        economyRenderer.addSeriesRenderer(renderer);
        legend = new StringBuilder();
        legend.append("<b><font color='").append(Integer.toString(colour)).append("'>").append(desc);
        legends.put(s.getKey(), legend.toString());
    }
    economyChart.repaint();

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