Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

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

Prototype

public static NumberFormat getInstance(Locale inLocale) 

Source Link

Document

Returns a general-purpose number format for the specified locale.

Usage

From source file:fr.cirad.mgdb.exporting.markeroriented.GFFExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }//w  w  w  . j  a va 2 s. c o m
        }

    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    int markerCount = markerCursor.count();

    List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs);
    ArrayList<String> individualList = new ArrayList<String>();
    for (int i = 0; i < sampleIDs.size(); i++) {
        Individual individual = individuals.get(i);
        if (!individualList.contains(individual.getId())) {
            individualList.add(individual.getId());
        }
    }

    String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals";
    zos.putNextEntry(new ZipEntry(exportName + ".gff3"));
    String header = "##gff-version 3" + LINE_SEPARATOR;
    zos.write(header.getBytes());

    TreeMap<String, String> typeToOntology = new TreeMap<String, String>();
    typeToOntology.put(Type.SNP.toString(), "SO:0000694");
    typeToOntology.put(Type.INDEL.toString(), "SO:1000032");
    typeToOntology.put(Type.MIXED.toString(), "SO:0001059");
    typeToOntology.put(Type.SYMBOLIC.toString(), "SO:0000109");
    typeToOntology.put(Type.MNP.toString(), "SO:0001059");

    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
    short nProgress = 0, nPreviousProgress = 0;
    long nLoadedMarkerCount = 0;

    while (markerCursor.hasNext()) {
        int nLoadedMarkerCountInLoop = 0;
        Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
        boolean fStartingNewChunk = true;
        markerCursor.batchSize(nChunkSize);
        while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
            DBObject exportVariant = markerCursor.next();
            DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
            markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                    refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                            + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
            nLoadedMarkerCountInLoop++;
            fStartingNewChunk = false;
        }

        List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet());
        LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes(
                mongoTemplate, sampleIDs, currentMarkers, true,
                null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes
        for (VariantData variant : variantsAndRuns.keySet()) // read data and write results into temporary files (one per sample)
        {
            Comparable variantId = variant.getId();
            List<String> variantDataOrigin = new ArrayList<String>();

            Map<String, Integer> gqValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, Integer> dpValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>();
            List<String> chromAndPos = Helper.split(markerChromosomalPositions.get(variantId), ":");
            if (chromAndPos.size() == 0)
                LOG.warn("Chromosomal position not found for marker " + variantId);
            // LOG.debug(marker + "\t" + (chromAndPos.length == 0 ? "0" : chromAndPos[0]) + "\t" + 0 + "\t" + (chromAndPos.length == 0 ? 0l : Long.parseLong(chromAndPos[1])) + LINE_SEPARATOR);
            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(variantId);
                if (syn != null)
                    variantId = syn;
            }

            Collection<VariantRunData> runs = variantsAndRuns.get(variant);
            if (runs != null)
                for (VariantRunData run : runs)
                    for (Integer sampleIndex : run.getSampleGenotypes().keySet()) {
                        SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex);
                        String individualId = individuals
                                .get(sampleIDs.indexOf(new SampleId(run.getId().getProjectId(), sampleIndex)))
                                .getId();

                        Integer gq = null;
                        try {
                            gq = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ);
                        } catch (Exception ignored) {
                        }
                        if (gq != null && gq < nMinimumGenotypeQuality)
                            continue;

                        Integer dp = null;
                        try {
                            dp = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP);
                        } catch (Exception ignored) {
                        }
                        if (dp != null && dp < nMinimumReadDepth)
                            continue;

                        String gtCode = sampleGenotype.getCode();
                        List<String> storedIndividualGenotypes = individualGenotypes.get(individualId);
                        if (storedIndividualGenotypes == null) {
                            storedIndividualGenotypes = new ArrayList<String>();
                            individualGenotypes.put(individualId, storedIndividualGenotypes);
                        }
                        storedIndividualGenotypes.add(gtCode);
                    }

            zos.write((chromAndPos.get(0) + "\t" + StringUtils.join(variantDataOrigin, ";") /*source*/ + "\t"
                    + typeToOntology.get(variant.getType()) + "\t" + Long.parseLong(chromAndPos.get(1)) + "\t"
                    + Long.parseLong(chromAndPos.get(1)) + "\t" + "." + "\t" + "+" + "\t" + "." + "\t")
                            .getBytes());
            Comparable syn = markerSynonyms == null ? null : markerSynonyms.get(variant.getId());
            zos.write(("ID=" + variant.getId() + ";" + (syn != null ? "Name=" + syn + ";" : "") + "alleles="
                    + StringUtils.join(variant.getKnownAlleleList(), "/") + ";" + "refallele="
                    + variant.getKnownAlleleList().get(0) + ";").getBytes());

            for (int j = 0; j < individualList
                    .size(); j++ /* we use this list because it has the proper ordering*/) {

                NumberFormat nf = NumberFormat.getInstance(Locale.US);
                nf.setMaximumFractionDigits(4);
                HashMap<String, Integer> compt1 = new HashMap<String, Integer>();
                int highestGenotypeCount = 0;
                int sum = 0;

                String individualId = individualList.get(j);
                List<String> genotypes = individualGenotypes.get(individualId);
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes

                String mostFrequentGenotype = null;
                if (genotypes != null)
                    for (String genotype : genotypes) {
                        if (genotype.length() == 0)
                            continue; /* skip missing genotypes */

                        int count = 0;
                        for (String t : variant.getAllelesFromGenotypeCode(genotype)) {
                            for (String t1 : variant.getKnownAlleleList()) {
                                if (t.equals(t1) && !(compt1.containsKey(t1))) {
                                    count++;
                                    compt1.put(t1, count);
                                } else if (t.equals(t1) && compt1.containsKey(t1)) {
                                    if (compt1.get(t1) != 0) {
                                        count++;
                                        compt1.put(t1, count);
                                    } else
                                        compt1.put(t1, count);
                                } else if (!(compt1.containsKey(t1))) {
                                    compt1.put(t1, 0);
                                }
                            }
                        }
                        for (int countValue : compt1.values()) {
                            sum += countValue;
                        }

                        int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                        if (gtCount > highestGenotypeCount) {
                            highestGenotypeCount = gtCount;
                            mostFrequentGenotype = genotype;
                        }
                        genotypeCounts.put(genotype, gtCount);
                    }

                List<String> alleles = mostFrequentGenotype == null ? new ArrayList<String>()
                        : variant.getAllelesFromGenotypeCode(mostFrequentGenotype);

                if (alleles.size() != 0) {
                    zos.write(("acounts=" + individualId + ":").getBytes());

                    for (String knowAllelesCompt : compt1.keySet()) {
                        zos.write(
                                (knowAllelesCompt + " " + nf.format(compt1.get(knowAllelesCompt) / (float) sum)
                                        + " " + compt1.get(knowAllelesCompt) + " ").getBytes());
                    }
                    zos.write((alleles.size() + ";").getBytes());
                }
                if (genotypeCounts.size() > 1) {
                    Comparable sVariantId = markerSynonyms != null ? markerSynonyms.get(variant.getId())
                            : variant.getId();
                    warningFileWriter.write("- Dissimilar genotypes found for variant "
                            + (sVariantId == null ? variant.getId() : sVariantId) + ", individual "
                            + individualId + ". Exporting most frequent: " + StringUtils.join(alleles, ",")
                            + "\n");
                }
            }
            zos.write((LINE_SEPARATOR).getBytes());
        }

        if (progress.hasAborted())
            return;

        nLoadedMarkerCount += nLoadedMarkerCountInLoop;
        nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
        if (nProgress > nPreviousProgress) {
            //            if (nProgress%5 == 0)
            //               LOG.info("========================= exportData: " + nProgress + "% =========================" + (System.currentTimeMillis() - before)/1000 + "s");
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
    }

    warningFileWriter.close();
    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:net.pms.util.Rational.java

/**
 * Returns an instance by parsing the specified {@link String}. The format
 * must be either {@code number/number}, {@code number:number} or
 * {@code number}. Signs are understood for both numerator and denominator.
 * If {@code value} is blank or {@code null}, {@code null} is returned. If
 * {@code value} can't be parsed, a {@link NumberFormatException} is thrown.
 *
 * @param value the {@link String} value to parse.
 * @param locale the {@link Locale} to use when parsing numbers. If
 *            {@code null}, "standard formatted" numbers are expected (no
 *            grouping, {@code .} as decimal separator etc.).
 * @return An instance that represents the value of {@code value}.
 * @throws NumberFormatException If {@code value} cannot be parsed.
 *///  www. j a  va  2  s. c om
@Nullable
public static Rational valueOf(@Nullable String value, @Nullable Locale locale) {
    return valueOf(value, locale == null ? null : NumberFormat.getInstance(locale));
}

From source file:mt.LengthDistribution.java

public static void GetLengthDistributionArrayatTime(ArrayList<File> AllMovies, double[] calibration,
        final int framenumber) {

    ArrayList<Double> maxlist = new ArrayList<Double>();
    for (int i = 0; i < AllMovies.size(); ++i) {

        ArrayList<Pair<Integer, Double>> lengthlist = LengthDistribution.LengthdistroatTime(AllMovies.get(i),
                framenumber);/*from ww  w .ja  va2s .c  o  m*/

        for (int index = 0; index < lengthlist.size(); ++index) {
            if (lengthlist.get(index).getB() != Double.NaN && lengthlist.get(index).getB() > 0)
                maxlist.add(lengthlist.get(index).getB());

        }
    }
    Collections.sort(maxlist);

    int min = 0;
    int max = 0;
    if (maxlist.size() > 0)
        max = (int) Math.round(maxlist.get(maxlist.size() - 1)) + 1;
    XYSeries counterseries = new XYSeries("MT length distribution");
    XYSeries Logcounterseries = new XYSeries("MT Log length distribution");
    final ArrayList<Point> points = new ArrayList<Point>();
    for (int length = 0; length < max; ++length) {

        HashMap<Integer, Integer> frameseed = new HashMap<Integer, Integer>();

        int count = 0;
        for (int i = 0; i < AllMovies.size(); ++i) {

            File file = AllMovies.get(i);

            ArrayList<FLSobject> currentobject = Tracking.loadMTStat(file);

            if (currentobject != null)
                for (int index = 0; index < currentobject.size(); ++index) {
                    ArrayList<Integer> seedlist = new ArrayList<Integer>();
                    if (currentobject.get(index).length >= length
                            && currentobject.get(index).Framenumber == framenumber) {
                        seedlist.add(currentobject.get(index).seedID);
                        if (frameseed.get(currentobject.get(index).Framenumber) != null
                                && frameseed.get(currentobject.get(index).Framenumber) != Double.NaN) {

                            int currentcount = frameseed.get(currentobject.get(index).Framenumber);
                            frameseed.put(currentobject.get(index).Framenumber, seedlist.size() + currentcount);
                        } else if (currentobject.get(index) != null)
                            frameseed.put(currentobject.get(index).Framenumber, seedlist.size());

                    }

                }

        }

        // Get maxima length, count
        int maxvalue = Integer.MIN_VALUE;

        for (int key : frameseed.keySet()) {

            int Count = frameseed.get(key);

            if (Count >= maxvalue)
                maxvalue = Count;
        }

        if (maxvalue != Integer.MIN_VALUE) {
            counterseries.add(length, maxvalue);

            if (maxvalue > 0) {

                System.out.println("Max " + maxvalue);
                Logcounterseries.add((length), Math.log(maxvalue));
                points.add(new Point(new double[] { length, Math.log(maxvalue) }));
            }

        }
    }

    final XYSeriesCollection dataset = new XYSeriesCollection();
    final XYSeriesCollection nofitdataset = new XYSeriesCollection();
    dataset.addSeries(counterseries);
    nofitdataset.addSeries(counterseries);
    final XYSeriesCollection Logdataset = new XYSeriesCollection();
    Logdataset.addSeries(Logcounterseries);

    final JFreeChart chart = ChartFactory.createScatterPlot("MT length distribution", "Number of MT",
            "Length (micrometer)", dataset);
    final JFreeChart nofitchart = ChartFactory.createScatterPlot("MT length distribution", "Number of MT",
            "Length (micrometer)", nofitdataset);
    // Fitting line to log of the length distribution
    interpolation.Polynomial poly = new interpolation.Polynomial(1);
    try {

        poly.fitFunction(points);

    } catch (NotEnoughDataPointsException e) {

    }
    DisplayPoints.display(nofitchart, new Dimension(800, 500));
    dataset.addSeries(Tracking.drawexpFunction(poly, counterseries.getMinX(), counterseries.getMaxX(), 0.5,
            "Exponential fit"));
    NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
    nf.setMaximumFractionDigits(3);
    TextTitle legendText = new TextTitle("Mean Length" + " : " + nf.format(-1.0 / poly.getCoefficients(1))
            + "  " + "Standard Deviation" + " : " + nf.format(poly.SSE));
    legendText.setPosition(RectangleEdge.RIGHT);

    DisplayPoints.display(chart, new Dimension(800, 500));
    chart.addSubtitle(legendText);

    System.out.println("Series count" + dataset.getSeriesCount());
    final JFreeChart logchart = ChartFactory.createScatterPlot("MT Log length distribution",
            "Length (micrometer)", "Number of MT", Logdataset);
    //     DisplayPoints.display(logchart, new Dimension(800, 500));
    for (int i = 1; i >= 0; --i)
        System.out.println(poly.getCoefficients(i) + "  " + "x" + " X to the power of " + i);

    //  Logdataset.addSeries(Tracking.drawFunction(poly, counterseries.getMinX(), counterseries.getMaxX(), 0.5, "Straight line fit"));
    WriteLengthdistroFile(AllMovies, counterseries, framenumber);
}

From source file:com.l2jfree.gameserver.util.Util.java

/**
 * Returns a number formatted with "," delimiter
 * //from w  w  w. j  a  v  a2 s .c o  m
 * @param value
 * @return String formatted number
 */
public static String formatNumber(long value) {
    return NumberFormat.getInstance(Locale.ENGLISH).format(value);
}

From source file:de.uka.aifb.com.systemDynamics.gui.ModelExecutionChartPanel.java

/**
 * Creates the XY line chart.//from w w  w .j a  v  a2  s. c  o m
 * 
 * @return XY line chart
 */
private JFreeChart createChart() {
    levelNodes = new LevelNode[model.getLevelNodes().size()];
    int i = 0;
    for (LevelNode levelNode : model.getLevelNodes()) {
        levelNodes[i++] = levelNode;
    }
    // sort level nodes alphabetically
    Arrays.sort(levelNodes);

    xySeriesArray = new XYSeries[levelNodes.length];
    XYSeriesCollection data = new XYSeriesCollection();
    for (i = 0; i < xySeriesArray.length; i++) {
        XYSeries xySeries = new XYSeries(levelNodes[i].getNodeName());
        xySeries.add(0.0, levelNodes[i].getCurrentValue());
        data.addSeries(xySeries);
        xySeriesArray[i] = xySeries;
    }
    nextRound = 1;

    chart = ChartFactory.createXYLineChart(null, messages.getString("ModelExecutionChartPanel.Round"),
            messages.getString("ModelExecutionChartPanel.Value"), data, PlotOrientation.VERTICAL, true, false,
            false);
    XYPlot plot = chart.getXYPlot();

    // horizontal axis range: 0 ... maximal rounds
    ((NumberAxis) (chart.getXYPlot().getDomainAxis())).setRangeType(RangeType.POSITIVE);
    plot.getDomainAxis().setAutoRangeMinimumSize(20);

    // only integer values as labels for horizontal axis
    plot.getDomainAxis().setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // number formatting according to current locale
    ((NumberAxis) (plot.getDomainAxis())).setNumberFormatOverride(NumberFormat.getIntegerInstance(locale));
    ((NumberAxis) (plot.getRangeAxis())).setNumberFormatOverride(NumberFormat.getInstance(locale));

    // legend at top position
    chart.getLegend().setPosition(RectangleEdge.TOP);

    return chart;
}

From source file:edu.kit.dama.rest.util.RestClientUtils.java

/**
 * Build REST URL from a given pattern and its values. There is no check for
 * correct number of arguments. While generating URL all arguments will
 * encoded to be in a correct format. E.g.: 'stupid example' will be
 * transformed to 'stupid%20example'./*from ww w  .j  ava  2 s  .c  o m*/
 *
 * @param pattern URL with any number of place holders for arguments
 * @param arguments array of arguments for the place holders
 * @return encoded URL
 */
public static String encodeUrl(String pattern, Object... arguments) {
    List<Object> urlArg = new ArrayList<>();
    for (Object arg : arguments) {
        if (arg == null) {
            throw new IllegalArgumentException("Null-values not supported for any element of 'arguments'.");
        }
        if (arg instanceof Number) {
            // everyting should work fine!
            NumberFormat instance = NumberFormat.getInstance(Locale.US);
            instance.setGroupingUsed(false);
            instance.setMaximumFractionDigits(9);
            String number = instance.format(arg);
            urlArg.add(number);
        } else if (arg instanceof String) {
            urlArg.add(encode((String) arg));
        } else {
            LOGGER.warn("Uncovered argument type {}", arg);
        }
    }
    String returnValue = MessageFormat.format(pattern, urlArg.toArray());

    LOGGER.debug("Final URL: {}", returnValue);

    return returnValue;
}

From source file:org.optaplanner.benchmark.impl.report.BenchmarkReport.java

private void writeBestScoreScalabilitySummaryChart() {
    // Each scoreLevel has it's own dataset and chartFile
    List<List<XYSeries>> seriesListList = new ArrayList<List<XYSeries>>(CHARTED_SCORE_LEVEL_SIZE);
    int solverBenchmarkIndex = 0;
    for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) {
        String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix();
        for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult
                .getSingleBenchmarkResultList()) {
            if (singleBenchmarkResult.isSuccess()) {
                long problemScale = singleBenchmarkResult.getProblemBenchmarkResult().getProblemScale();
                double[] levelValues = ScoreUtils.extractLevelDoubles(singleBenchmarkResult.getScore());
                for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) {
                    if (i >= seriesListList.size()) {
                        seriesListList.add(new ArrayList<XYSeries>(
                                plannerBenchmarkResult.getSolverBenchmarkResultList().size()));
                    }/*from  w  ww. ja  v a2s.  c o m*/
                    List<XYSeries> seriesList = seriesListList.get(i);
                    while (solverBenchmarkIndex >= seriesList.size()) {
                        seriesList.add(new XYSeries(solverLabel));
                    }
                    seriesList.get(solverBenchmarkIndex).add((double) problemScale, levelValues[i]);
                }
            }
        }
        solverBenchmarkIndex++;
    }
    bestScoreScalabilitySummaryChartFileList = new ArrayList<File>(seriesListList.size());
    int scoreLevelIndex = 0;
    for (List<XYSeries> seriesList : seriesListList) {
        XYPlot plot = createScalabilityPlot(seriesList, "Problem scale", NumberFormat.getInstance(locale),
                "Score level " + scoreLevelIndex, NumberFormat.getInstance(locale));
        JFreeChart chart = new JFreeChart(
                "Best score scalability level " + scoreLevelIndex + " summary (higher is better)",
                JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        bestScoreScalabilitySummaryChartFileList
                .add(writeChartToImageFile(chart, "bestScoreScalabilitySummaryLevel" + scoreLevelIndex));
        scoreLevelIndex++;
    }
}

From source file:com.chart.SwingChart.java

/**
 * //w ww  .j a  v  a  2  s  .  com
 * @param name Chart name
 * @param parent Skeleton parent
 * @param axes Configuration of axes
 * @param abcissaName Abcissa name
 */
public SwingChart(String name, final Skeleton parent, List<AxisChart> axes, String abcissaName) {
    this.skeleton = parent;
    this.axes = axes;
    this.name = name;

    this.abcissaFormat = NumberFormat.getInstance(Locale.getDefault());
    this.ordinateFormat = NumberFormat.getInstance(Locale.getDefault());

    plot = new XYPlot();
    plot.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strChartBackgroundColor)));
    plot.setDomainGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setRangeGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    abcissaAxis = new NumberAxis(abcissaName);
    ((NumberAxis) abcissaAxis).setAutoRangeIncludesZero(false);
    abcissaAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setAutoRange(true);
    abcissaAxis.setLowerMargin(0.0);
    abcissaAxis.setUpperMargin(0.0);
    abcissaAxis.setTickLabelsVisible(true);
    abcissaAxis.setLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));
    abcissaAxis.setTickLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));

    plot.setDomainAxis(abcissaAxis);

    for (int i = 0; i < axes.size(); i++) {
        AxisChart categoria = axes.get(i);
        addAxis(categoria.getName());

        for (int j = 0; j < categoria.configSerieList.size(); j++) {
            SimpleSeriesConfiguration cs = categoria.configSerieList.get(j);
            addSeries(categoria.getName(), cs);
        }
    }
    chart = new JFreeChart("", new Font("SansSerif", Font.BOLD, 16), plot, false);

    chart.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
            BorderFactory.createLineBorder(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)))));

    chartPanel.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escape");
    chartPanel.getActionMap().put("escape", new AbstractAction() {

        @Override
        public void actionPerformed(java.awt.event.ActionEvent e) {
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                XYDataset test = plot.getDataset(i);
                XYItemRenderer r = plot.getRenderer(i);
                r.removeAnnotations();
            }
        }
    });

    chartPanel.addChartMouseListener(cml = new ChartMouseListener() {
        @Override
        public void chartMouseClicked(ChartMouseEvent event) {
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent event) {
            try {
                XYItemEntity xyitem = (XYItemEntity) event.getEntity(); // get clicked entity
                XYDataset dataset = (XYDataset) xyitem.getDataset(); // get data set    
                double x = dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem());
                double y = dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem());

                final XYPlot plot = chart.getXYPlot();
                for (int i = 0; i < plot.getDatasetCount(); i++) {
                    XYDataset test = plot.getDataset(i);
                    XYItemRenderer r = plot.getRenderer(i);
                    r.removeAnnotations();
                    if (test == dataset) {
                        NumberAxis ejeOrdenada = AxesList.get(i);
                        double y_max = ejeOrdenada.getUpperBound();
                        double y_min = ejeOrdenada.getLowerBound();
                        double x_max = abcissaAxis.getUpperBound();
                        double x_min = abcissaAxis.getLowerBound();
                        double angulo;
                        if (y > (y_max + y_min) / 2 && x > (x_max + x_min) / 2) {
                            angulo = 3.0 * Math.PI / 4.0;
                        } else if (y > (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                            angulo = 1.0 * Math.PI / 4.0;
                        } else if (y < (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                            angulo = 7.0 * Math.PI / 4.0;
                        } else {
                            angulo = 5.0 * Math.PI / 4.0;
                        }

                        CircleDrawer cd = new CircleDrawer((Color) r.getSeriesPaint(xyitem.getSeriesIndex()),
                                new BasicStroke(2.0f), null);
                        //XYAnnotation bestBid = new XYDrawableAnnotation(dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), 11, 11, cd);
                        String txt = "X:" + abcissaFormat.format(x) + ", Y:" + ordinateFormat.format(y);
                        XYPointerAnnotation anotacion = new XYPointerAnnotation(txt,
                                dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()),
                                dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), angulo);
                        anotacion.setTipRadius(10.0);
                        anotacion.setBaseRadius(35.0);
                        anotacion.setFont(new Font("SansSerif", Font.PLAIN, 10));

                        if (Long.parseLong((strChartBackgroundColor.replace("#", "")), 16) > 0xffffff / 2) {
                            anotacion.setPaint(Color.black);
                            anotacion.setArrowPaint(Color.black);
                        } else {
                            anotacion.setPaint(Color.white);
                            anotacion.setArrowPaint(Color.white);
                        }

                        //bestBid.setPaint((Color) r.getSeriesPaint(xyitem.getSeriesIndex()));
                        r.addAnnotation(anotacion);
                    }
                }

                //LabelValorVariable.setSize(LabelValorVariable.getPreferredSize());
            } catch (NullPointerException | ClassCastException ex) {

            }
        }
    });

    chartPanel.setPopupMenu(null);
    chartPanel.setBackground(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    SwingNode sn = new SwingNode();
    sn.setContent(chartPanel);
    chartFrame = new VBox();
    chartFrame.getChildren().addAll(sn, legendFrame);
    VBox.setVgrow(sn, Priority.ALWAYS);
    VBox.setVgrow(legendFrame, Priority.NEVER);

    chartFrame.getStylesheets().addAll(SwingChart.class.getResource("overlay-chart.css").toExternalForm());

    legendFrame.setStyle("marco: " + strBackgroundColor + ";-fx-background-color: marco;");

    MenuItem mi;
    mi = new MenuItem("Print");
    mi.setOnAction((ActionEvent t) -> {
        print(chartFrame);
    });
    contextMenuList.add(mi);

    sn.setOnMouseClicked((MouseEvent t) -> {
        if (menu != null) {
            menu.hide();
        }
        if (t.getClickCount() == 2) {
            backgroundEdition();
        }
    });

    mi = new MenuItem("Copy to clipboard");
    mi.setOnAction((ActionEvent t) -> {
        copyClipboard(chartFrame);
    });
    contextMenuList.add(mi);

    mi = new MenuItem("Export values");
    mi.setOnAction((ActionEvent t) -> {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Export to file");
        fileChooser.getExtensionFilters()
                .addAll(new FileChooser.ExtensionFilter("Comma Separated Values", "*.csv"));

        Window w = null;
        try {
            w = parent.getScene().getWindow();
        } catch (NullPointerException e) {

        }
        File file = fileChooser.showSaveDialog(w);
        if (file != null) {
            export(file);
        }
    });
    contextMenuList.add(mi);

    chartFrame.setOnContextMenuRequested((ContextMenuEvent t) -> {
        if (menu != null) {
            menu.hide();
        }
        menu = new ContextMenu();
        menu.getItems().addAll(contextMenuList);
        menu.show(chartFrame, t.getScreenX(), t.getScreenY());
    });

}

From source file:org.drools.planner.benchmark.core.report.BenchmarkReport.java

private void writeWinningScoreDifferenceSummaryChart() {
    // Each scoreLevel has it's own dataset and chartFile
    List<DefaultCategoryDataset> datasetList = new ArrayList<DefaultCategoryDataset>(CHARTED_SCORE_LEVEL_SIZE);
    for (SolverBenchmark solverBenchmark : plannerBenchmark.getSolverBenchmarkList()) {
        String solverLabel = solverBenchmark.getNameWithFavoriteSuffix();
        for (SingleBenchmark singleBenchmark : solverBenchmark.getSingleBenchmarkList()) {
            String planningProblemLabel = singleBenchmark.getProblemBenchmark().getName();
            if (singleBenchmark.isSuccess()) {
                double[] levelValues = singleBenchmark.getWinningScoreDifference().toDoubleLevels();
                for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) {
                    if (i >= datasetList.size()) {
                        datasetList.add(new DefaultCategoryDataset());
                    }//from   w w w.  j a  v  a2 s  .  c o m
                    datasetList.get(i).addValue(levelValues[i], solverLabel, planningProblemLabel);
                }
            }
        }
    }
    winningScoreDifferenceSummaryChartFileList = new ArrayList<File>(datasetList.size());
    int scoreLevelIndex = 0;
    for (DefaultCategoryDataset dataset : datasetList) {
        CategoryPlot plot = createBarChartPlot(dataset, "Winning score difference level " + scoreLevelIndex,
                NumberFormat.getInstance(locale));
        JFreeChart chart = new JFreeChart(
                "Winning score difference level " + scoreLevelIndex + " summary (higher is better)",
                JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        winningScoreDifferenceSummaryChartFileList
                .add(writeChartToImageFile(chart, "winningScoreDifferenceSummaryLevel" + scoreLevelIndex));
        scoreLevelIndex++;
    }
}