Example usage for org.jfree.chart JFreeChart getTitle

List of usage examples for org.jfree.chart JFreeChart getTitle

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart getTitle.

Prototype

public TextTitle getTitle() 

Source Link

Document

Returns the main chart title.

Usage

From source file:edu.ucla.stat.SOCR.chart.SuperPieChart.java

/**
 * Creates a chart.//  ww w.  j a v  a2 s.  co m
 * 
 * @param dataset  the dataset.
 * 
 * @return a chart.
 */
protected JFreeChart createChart(PieDataset dataset) {

    JFreeChart chart = ChartFactory.createPieChart(chartTitle, // chart title
            dataset, // data
            !legendPanelOn, // include legend
            true, false);
    TextTitle title = chart.getTitle();
    title.setToolTipText("A title tooltip!");

    PiePlot plot = (PiePlot) chart.getPlot();
    if (!ThreeDPie) {
        for (int i = 0; i < pulloutFlag.length; i++) {
            //System.out.println("SuperPieChart\""+pulloutFlag[i]+"\"");
            if (pulloutFlag[i].equals("1")) {
                Comparable key = dataset.getKey(i);
                plot.setExplodePercent(key, 0.30);
            }
        }
    }
    plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    plot.setNoDataMessage("No data available");
    plot.setCircular(false);
    plot.setLabelGap(0.02);

    return chart;
}

From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java

protected JFreeChart getFutureForecastChart(TSForecaster forecaster, List<List<NumericPrediction>> preds,
        List<String> targetNames, Instances history) {

    if (forecaster instanceof TSLagUser && history != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) {

            // fill in any missing time stamps only
            history = new Instances(history);
            history = weka.classifiers.timeseries.core.Utils.replaceMissing(history, null,
                    lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries());
        }/*  w  w w .j ava 2  s.  c o  m*/
    }

    // set up a collection of series
    XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection();

    if (history != null) {
        // add actual historical data values
        for (String targetName : targetNames) {
            XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false, false);
            xyDataset.addSeries(targetSeries);
        }
    }

    // add predicted series
    for (String targetName : targetNames) {
        XYIntervalSeries targetSeries = new XYIntervalSeries(targetName + "-predicted", false, false);
        xyDataset.addSeries(targetSeries);
    }

    ValueAxis timeAxis = null;
    NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false);
    int timeIndex = -1;
    boolean timeAxisIsDate = false;
    double artificialTimeStart = 0;
    double lastRealTimeValue = Utils.missingValue();
    if (forecaster instanceof TSLagUser && history != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) {
            String timeName = lagMaker.getTimeStampField();
            if (history.attribute(timeName).isDate()) {
                timeAxis = new DateAxis("");
                timeAxisIsDate = true;
                timeIndex = history.attribute(timeName).index();
            }
        } else {
            try {
                artificialTimeStart = (history != null) ? 1 : lagMaker.getArtificialTimeStartValue() + 1;
            } catch (Exception ex) {
            }
        }
    }

    if (timeAxis == null) {
        timeAxis = new NumberAxis("");
        ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false);
    }

    boolean hasConfidenceIntervals = false;

    // now populate the series
    if (history != null) {

        // do the actuals first
        for (int i = 0; i < history.numInstances(); i++) {
            Instance current = history.instance(i);

            for (String targetName : targetNames) {
                int dataIndex = history.attribute(targetName.trim()).index();

                if (dataIndex >= 0) {
                    XYIntervalSeries actualSeries = null;
                    int actualIndex = xyDataset.indexOf(targetName);
                    actualSeries = xyDataset.getSeries(actualIndex);
                    double x = Utils.missingValue();

                    if (timeAxisIsDate) {
                        x = current.value(timeIndex);
                        if (!Utils.isMissingValue(x)) {
                            lastRealTimeValue = x;
                        }
                    } else {
                        x = artificialTimeStart;
                    }

                    double y = Utils.missingValue();
                    y = current.value(dataIndex);

                    if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
                        if (actualSeries != null) {
                            actualSeries.add(x, x, x, y, y, y);
                        }
                    }
                }
            }

            if (!timeAxisIsDate) {
                artificialTimeStart++;
            }
        }
    }

    // now do the futures
    List<String> forecasterTargets = AbstractForecaster.stringToList(forecaster.getFieldsToForecast());

    // loop over the steps
    for (int j = 0; j < preds.size(); j++) {
        List<NumericPrediction> predsForStepJ = preds.get(j);

        // advance the real time index (if appropriate)
        if (timeAxisIsDate) {
            lastRealTimeValue = ((TSLagUser) forecaster).getTSLagMaker()
                    .advanceSuppliedTimeValue(lastRealTimeValue);
        }
        for (String targetName : targetNames) {

            // look up this requested target in the list that the forecaster
            // has predicted
            int predIndex = forecasterTargets.indexOf(targetName.trim());
            if (predIndex >= 0) {
                NumericPrediction predsForTargetAtStepJ = predsForStepJ.get(predIndex);
                XYIntervalSeries predSeries = null;
                int datasetIndex = xyDataset.indexOf(targetName + "-predicted");
                predSeries = xyDataset.getSeries(datasetIndex);

                if (predSeries != null) {
                    double y = predsForTargetAtStepJ.predicted();
                    double x = Utils.missingValue();
                    double yHigh = y;
                    double yLow = y;
                    double[][] conf = predsForTargetAtStepJ.predictionIntervals();
                    if (conf.length > 0) {
                        yLow = conf[0][0];
                        yHigh = conf[0][1];
                        hasConfidenceIntervals = true;
                    }

                    if (!timeAxisIsDate) {
                        x = artificialTimeStart;
                    } else {
                        x = lastRealTimeValue;
                    }

                    if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
                        predSeries.add(x, x, x, y, yLow, yHigh);
                    }
                }
            }
        }

        // advance the artificial time index (if appropriate)
        if (!timeAxisIsDate) {
            artificialTimeStart++;
        }
    }

    String title = "Future forecast for: ";
    for (String s : targetNames) {
        title += s + ",";
    }
    title = title.substring(0, title.lastIndexOf(","));

    /*
     * String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec
     * + ")";
     */

    if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) {
        double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0;
        title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]";
    }

    XYErrorRenderer renderer = new XYErrorRenderer();

    // renderer.setShapesFilled(true);
    XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer);
    // renderer = (XYErrorRenderer)plot.getRenderer();
    if (history != null) {
        for (String targetName : targetNames) {
            XYIntervalSeries predSeries = null;
            int predIndex = xyDataset.indexOf(targetName + "-predicted");
            predSeries = xyDataset.getSeries(predIndex);

            XYIntervalSeries actualSeries = null;
            int actualIndex = xyDataset.indexOf(targetName);
            actualSeries = xyDataset.getSeries(actualIndex);

            if (actualSeries != null && predSeries != null) {
                // match the color of the actual series
                java.awt.Paint actualPaint = renderer.lookupSeriesPaint(actualIndex);
                renderer.setSeriesPaint(predIndex, actualPaint);

                // now set the line style to dashed
                BasicStroke dashed = new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f,
                        new float[] { 5.0f }, 0.0f);

                renderer.setSeriesStroke(predIndex, dashed);
            }
        }
    }

    renderer.setBaseLinesVisible(true);
    renderer.setDrawXError(false);
    renderer.setDrawYError(true);

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    chart.setBackgroundPaint(java.awt.Color.white);
    TextTitle chartTitle = chart.getTitle();
    String fontName = chartTitle.getFont().getFontName();
    java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12);
    chartTitle.setFont(newFont);

    return chart;
}

From source file:Gui.HistoryAdminGUINew.java

public void showStatHistory() {
    // method statGreensociety......  History 
    int tempRepair = history.statGreensocietyRepair();
    int tempBorrow = history.statGreensocietyBorrow();
    int tempReturn = history.statGreensocietyReturn();
    DefaultCategoryDataset barchartData = new DefaultCategoryDataset();

    barchartData.setValue(tempRepair, "0", "RepairHistory");
    barchartData.setValue(tempBorrow, "1", "BorrowHistory");
    barchartData.setValue(tempReturn, "2", "ReturnHistory");

    JFreeChart chart = ChartFactory.createBarChart("History Statictics", "History", "Times", barchartData,
            PlotOrientation.HORIZONTAL, false, true, false);

    //        chart.getTitle().setPaint(Color.WHITE);   //??

    //--------SET FONT--------------
    try {//from  w w  w.j  av a2  s  .  com
        File f = new File("leelawad.ttf");
        Font customFont = Font.createFont(Font.TRUETYPE_FONT, f);
        customFont = customFont.deriveFont(16f);
        chart.getTitle().setFont(customFont);
        System.out.println(customFont.getFontName());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (FontFormatException | IOException e) {
        e.printStackTrace();
    }
    //------------------------------
    chart.setBackgroundPaint(new Color(19, 175, 248)); //setBackground ?

    CategoryPlot barchartPlot = chart.getCategoryPlot();

    barchartPlot.setRangeGridlinePaint(Color.BLACK); //set ??

    //Customize renderer
    BarRenderer renderer = (BarRenderer) barchartPlot.getRenderer();
    java.awt.Paint paint1 = new Color(255, 0, 0);
    java.awt.Paint paint2 = new Color(0, 0, 255);
    java.awt.Paint paint3 = new Color(255, 255, 0);

    renderer.setSeriesPaint(0, paint1); //Color for RepairGraph
    renderer.setSeriesPaint(1, paint2); //Color for BorrowGraph
    renderer.setSeriesPaint(2, paint3); //Color for ReturnGraph

    ChartPanel barPanel = new ChartPanel(chart);
    jPanelShowGraph.removeAll();
    jPanelShowGraph.add(barPanel, BorderLayout.CENTER);
    jPanelShowGraph.validate();
}

From source file:com.polivoto.vistas.Charts.java

private void crearBarChart(Pregunta pregunta) {
    JPanel panel = new JPanel(new BorderLayout());
    panel.setBackground(Color.white);
    panelGrafica.add(panel);//from   w w  w  . ja va2  s . c  om

    DefaultCategoryDataset data = new DefaultCategoryDataset();
    // Fuente de Datos

    //Calcular el nmero N de perfiles. Si N=1, no discriminar por pestanas. 
    //Si son N perfiles (N>2), hacer N+1 pestanas (la ltima representa la
    //suma de los resultados sin segregacin.
    int n = pregunta.obtenerCantidadDePerfiles();
    System.out.println(" n " + n);
    if (n > 1) {
        for (int i = 0; i < n; i++) {
            List<Opcion> opciones = pregunta.obtenerResultadoPorPerfil(i).getOpciones();
            for (Opcion opc : opciones) {
                data.setValue(opc.getCantidad(), opc.getNombre(),
                        pregunta.obtenerResultadoPorPerfil(i).getPerfil());
            }
        }
    }
    for (int i = 0; i < pregunta.obtenerCantidadDeOpciones(); i++) {
        Opcion opc = pregunta.obtenerOpcion(i);
        data.setValue(opc.getCantidad(), opc.getNombre(), "Todos");
    }

    // Creando el Grafico       
    JFreeChart chart = ChartFactory.createBarChart("\n" + pregunta.getTitulo() + "\n", "Perfil",
            "Total de votos", data, PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips?
            false // URLs?
    );

    //chart.setBackgroundPaint(Color.white);
    chart.getTitle().setFont(new Font("Roboto", 0, 28));

    //chart.addSubtitle(new TextTitle("Titulo jajaja"));
    //chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.white));
    CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.DARK_GRAY);
    plot.setOutlineVisible(false);

    ChartPanel barChart = new ChartPanel(chart);
    barChart.setBounds(panel.getVisibleRect());

    //barChart.setPreferredSize(panelGrafica.getSize());
    //barChart.setBounds(panel.getVisibleRect());

    //Colores de Barras
    Paint[] colors = { new Color(124, 181, 236), new Color(244, 91, 91), new Color(144, 237, 125),
            new Color(67, 67, 72), new Color(247, 163, 92), new Color(128, 133, 233), new Color(241, 92, 128),
            new Color(228, 211, 84), new Color(43, 144, 143), new Color(145, 232, 225) };

    ((org.jfree.chart.renderer.category.BarRenderer) plot.getRenderer())
            .setBarPainter(new StandardBarPainter()); // Quita Efecto luz
    BarRenderer renderer = new BarRenderer(colors);
    renderer.setColor(plot, data);

    //Numeros sobre barras
    CategoryItemRenderer renderizar;
    renderizar = plot.getRenderer();
    renderizar.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    renderizar.setBaseItemLabelsVisible(true);
    renderizar.setItemLabelFont(new Font("Roboto", 0, 18));

    //Valores eje Y
    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setLabelFont(new Font("Roboto", 0, 17));
    rangeAxis.setTickLabelFont(new Font("Roboto", 0, 17));

    //Diseo categorias
    org.jfree.chart.axis.CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLabelFont(new Font("Roboto", 0, 17));
    domainAxis.setTickLabelFont(new Font("Roboto", 0, 17));
    /*domainAxis.setTickLabelPaint(new Color(160, 163, 165));
     domainAxis.setCategoryLabelPositionOffset(4);
     domainAxis.setLowerMargin(0);
     domainAxis.setUpperMargin(0);
     domainAxis.setCategoryMargin(0.2);
     */

    //Leyendas
    LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.BOTTOM);
    Font nwfont = new Font("Roboto", 0, 18);
    legend.setItemFont(nwfont);
    legend.setBorder(0, 0, 0, 0);
    legend.setBackgroundPaint(Color.WHITE);
    legend.setItemLabelPadding(new RectangleInsets(8, 8, 8, 15));

    /*
     plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{1} {0}"));
     plot.setLegendItemShape(new Rectangle(25, 25));
     */
    // Pintar
    panel.removeAll();
    panel.add(barChart);
    panel.repaint();
    panel.revalidate();
    panelGrafica.repaint();
    panelGrafica.revalidate();
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.GpsScatterPlotUIComponent.java

/***********************************************************************************************
 * Customise the XYPlot of a new chart, e.g. for fixed range axes.
 * Remember that a GPS Scatter Plot has no ChannelSelector.
 *
 * @param datasettype//from ww w. jav a 2 s.c  om
 * @param primarydataset
 * @param secondarydatasets
 * @param updatetype
 * @param displaylimit
 * @param channelselector
 * @param debug
 *
 * @return JFreeChart
 */

public JFreeChart createCustomisedChart(final DatasetType datasettype, final XYDataset primarydataset,
        final List<XYDataset> secondarydatasets, final DataUpdateType updatetype, final int displaylimit,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final String SOURCE = "GpsScatterPlotUIComponent.createCustomisedChart() ";
    final JFreeChart jFreeChart;
    final XYPlot plot;
    final Stroke strokeCrosshair;
    final XYDotRenderer renderer;
    final ValueAxis axisRange;
    final NumberAxis axisDomain;

    // See ChartHelper for other calls to ChartFactory
    // Note that no ChannelSector means no way to control the legend, so turn it off
    jFreeChart = ChartFactory.createScatterPlot(MSG_WAITING_FOR_DATA, MSG_WAITING_FOR_DATA,
            MSG_WAITING_FOR_DATA, primarydataset, PlotOrientation.VERTICAL, false, //channelselector.hasLegend(),
            true, false);

    jFreeChart.setBackgroundPaint(UIComponentPlugin.DEFAULT_COLOUR_CANVAS.getColor());

    // Experimental chart configuration
    jFreeChart.getTitle().setFont(UIComponentPlugin.DEFAULT_FONT.getFont().deriveFont(20.0f));

    plot = (XYPlot) jFreeChart.getPlot();

    plot.setBackgroundPaint(ChartHelper.COLOR_PLOT);
    plot.setDomainGridlinePaint(ChartHelper.COLOR_GRIDLINES);
    plot.setRangeGridlinePaint(ChartHelper.COLOR_GRIDLINES);
    plot.setAxisOffset(ChartHelper.PLOT_RECTANGLE_INSETS);

    plot.setDomainZeroBaselineVisible(true);
    plot.setRangeZeroBaselineVisible(true);

    plot.setDomainCrosshairVisible(true);
    plot.setDomainCrosshairLockedOnData(false);

    plot.setRangeCrosshairVisible(true);
    plot.setRangeCrosshairLockedOnData(true);

    // Make the Crosshair more visible by changing the width from the default
    strokeCrosshair = new BasicStroke(2.0f, // The width of this BasicStroke
            BasicStroke.CAP_BUTT, // The decoration of the ends of a BasicStroke
            BasicStroke.JOIN_BEVEL, // The decoration applied where path segments meet
            0.0f, // The limit to trim the miter join
            new float[] { 2.0f, 2.0f }, // The array representing the dashing pattern
            0.0f); // The offset to start the dashing pattern
    plot.setDomainCrosshairStroke(strokeCrosshair);
    plot.setRangeCrosshairStroke(strokeCrosshair);

    renderer = new XYDotRenderer();
    renderer.setDotWidth(2);
    renderer.setDotHeight(2);
    plot.setRenderer(renderer);

    axisDomain = (NumberAxis) plot.getDomainAxis();
    axisRange = plot.getRangeAxis();

    // Remember that a GPS Scatter Plot has no ChannelSelector
    if (canAutorange()) {
        // The fix could be anywhere...
        axisDomain.setAutoRangeIncludesZero(false);
        axisDomain.setAutoRange(true);
        axisRange.setAutoRange(true);
    } else {
        // Allow range to full global extents!
        axisDomain.setRange(getLinearFixedMinY(), getLinearFixedMaxY());
        axisRange.setRange(-90.0, 90.0);
    }

    return (jFreeChart);
}

From source file:net.sf.mzmine.modules.visualization.tic.TICPlot.java

public TICPlot(final ActionListener listener) {

    super(null, true);

    // Initialize.
    visualizer = listener;/*from   ww w.ja  v  a 2 s.  c  o m*/
    labelsVisible = 1;
    havePeakLabels = false;
    numOfDataSets = 0;
    numOfPeaks = 0;
    showSpectrumRequest = false;

    // Set cursor.
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

    // Y-axis label.
    final String yAxisLabel;
    if (listener instanceof TICVisualizerWindow) {

        yAxisLabel = ((TICVisualizerWindow) listener).getPlotType() == PlotType.BASEPEAK ? "Base peak intensity"
                : "Total ion intensity";
    } else {

        yAxisLabel = "Base peak intensity";
    }

    // Initialize the chart by default time series chart from factory.
    final JFreeChart chart = ChartFactory.createXYLineChart("", // title
            "Retention time", // x-axis label
            yAxisLabel, // y-axis label
            null, // data set
            PlotOrientation.VERTICAL, // orientation
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );
    chart.setBackgroundPaint(Color.white);
    setChart(chart);

    // Title.
    chartTitle = chart.getTitle();
    chartTitle.setFont(TITLE_FONT);
    chartTitle.setMargin(TITLE_TOP_MARGIN, 0.0, 0.0, 0.0);

    // Subtitle.
    chartSubTitle = new TextTitle();
    chartSubTitle.setFont(SUBTITLE_FONT);
    chartSubTitle.setMargin(TITLE_TOP_MARGIN, 0.0, 0.0, 0.0);
    chart.addSubtitle(chartSubTitle);

    // Disable maximum size (we don't want scaling).
    setMaximumDrawWidth(Integer.MAX_VALUE);
    setMaximumDrawHeight(Integer.MAX_VALUE);

    // Legend constructed by ChartFactory.
    final LegendTitle legend = chart.getLegend();
    legend.setItemFont(LEGEND_FONT);
    legend.setFrame(BlockBorder.NONE);

    // Set the plot properties.
    plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setAxisOffset(AXIS_OFFSET);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    // Set grid properties.
    plot.setDomainGridlinePaint(GRID_COLOR);
    plot.setRangeGridlinePaint(GRID_COLOR);

    // Set cross-hair (selection) properties.
    if (listener instanceof TICVisualizerWindow) {

        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);
        plot.setDomainCrosshairPaint(CROSS_HAIR_COLOR);
        plot.setRangeCrosshairPaint(CROSS_HAIR_COLOR);
        plot.setDomainCrosshairStroke(CROSS_HAIR_STROKE);
        plot.setRangeCrosshairStroke(CROSS_HAIR_STROKE);
    }

    // Set the x-axis (retention time) properties.
    final NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setNumberFormatOverride(MZmineCore.getConfiguration().getRTFormat());
    xAxis.setUpperMargin(AXIS_MARGINS);
    xAxis.setLowerMargin(AXIS_MARGINS);

    // Set the y-axis (intensity) properties.
    final NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setNumberFormatOverride(MZmineCore.getConfiguration().getIntensityFormat());

    // Set default renderer properties.
    defaultRenderer = new TICPlotRenderer();
    defaultRenderer.setBaseShapesFilled(true);
    defaultRenderer.setDrawOutlines(false);
    defaultRenderer.setUseFillPaint(true);
    defaultRenderer.setBaseItemLabelPaint(LABEL_COLOR);

    // Set label generator
    final XYItemLabelGenerator labelGenerator = new TICItemLabelGenerator(this);
    defaultRenderer.setBaseItemLabelGenerator(labelGenerator);
    defaultRenderer.setBaseItemLabelsVisible(true);

    // Set toolTipGenerator
    final XYToolTipGenerator toolTipGenerator = new TICToolTipGenerator();
    defaultRenderer.setBaseToolTipGenerator(toolTipGenerator);

    // Set focus state to receive key events.
    setFocusable(true);

    // Register key handlers.
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke("LEFT"), listener, "MOVE_CURSOR_LEFT");
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke("RIGHT"), listener, "MOVE_CURSOR_RIGHT");
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke("SPACE"), listener, "SHOW_SPECTRUM");
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke('+'), this, "ZOOM_IN");
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke('-'), this, "ZOOM_OUT");

    // Add items to popup menu.
    final JPopupMenu popupMenu = getPopupMenu();
    popupMenu.addSeparator();

    if (listener instanceof TICVisualizerWindow) {

        popupMenu.add(new ExportPopUpMenu((TICVisualizerWindow) listener));
        popupMenu.addSeparator();
        popupMenu.add(new AddFilePopupMenu((TICVisualizerWindow) listener));
        popupMenu.add(new RemoveFilePopupMenu((TICVisualizerWindow) listener));
        popupMenu.add(new ExportPopUpMenu((TICVisualizerWindow) listener));
        popupMenu.addSeparator();
    }

    GUIUtils.addMenuItem(popupMenu, "Toggle showing peak values", this, "SHOW_ANNOTATIONS");
    GUIUtils.addMenuItem(popupMenu, "Toggle showing data points", this, "SHOW_DATA_POINTS");

    if (listener instanceof TICVisualizerWindow) {
        popupMenu.addSeparator();
        GUIUtils.addMenuItem(popupMenu, "Show spectrum of selected scan", listener, "SHOW_SPECTRUM");
    }

    popupMenu.addSeparator();

    GUIUtils.addMenuItem(popupMenu, "Set axes range", this, "SETUP_AXES");

    if (listener instanceof TICVisualizerWindow) {

        GUIUtils.addMenuItem(popupMenu, "Set same range to all windows", this, "SET_SAME_RANGE");
    }
}

From source file:com.mxgraph.examples.swing.chart.BarChartDemo1.java

/**
 * Creates a sample chart./*  w ww  . jav a2s.  c  o m*/
 *
 * @param dataset  the dataset.
 *
 * @return The chart.
 */
public static JFreeChart createChart(final CategoryDataset dataset) {
    // create the chart...
    JFreeChart chart = ChartFactory.createBarChart("", // chart title
            "X-value", // domain axis label
            "Y-value", // range axis label
            dataset, // data
            PlotOrientation.HORIZONTAL, // orientation
            true, // include legend
            true, false);
    chart.addSubtitle(new TextTitle("http://www.bupt.edu.cn", new Font("", Font.ITALIC, 10)));
    //   chart.setBackgroundPaint(Color.white);
    //   chart.setBackgroundPaint(Color.getHSBColor(2, 29, 100));
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.white);
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setBaseItemLabelsVisible(true);

    //
    renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setCategoryMargin(0.1);//
    categoryAxis.setUpperMargin(0.02);
    categoryAxis.setLowerMargin(0.02);
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setUpperMargin(0.10);

    // set up gradient paints for series...
    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0));
    GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(64, 0, 0));
    renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);
    renderer.setSeriesPaint(2, gp2);

    chart.getTitle().setFont(new Font("", Font.PLAIN, 16));//

    CategoryAxis domainAxis = plot.getDomainAxis();
    //
    domainAxis.setLabelFont(new Font("", Font.PLAIN, 14));
    //
    domainAxis.setTickLabelFont(new Font("", Font.PLAIN, 10));

    //
    rangeAxis.setLabelFont(new Font("", Font.PLAIN, 15));

    chart.getLegend().setItemFont(new Font("", Font.PLAIN, 15));

    return chart;
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.AbstractChartExpression.java

protected void configureChart(final JFreeChart chart) {
    // Misc Properties
    final TextTitle chartTitle = chart.getTitle();
    if (chartTitle != null) {
        final Font titleFont = Font.decode(getTitleFont());
        chartTitle.setFont(titleFont);//from   ww  w .  jav  a 2s .com
    }

    if (isAntiAlias() == false) {
        chart.setAntiAlias(false);
    }

    chart.setBorderVisible(isShowBorder());

    final Color backgroundColor = parseColorFromString(getBackgroundColor());
    if (backgroundColor != null) {
        chart.setBackgroundPaint(backgroundColor);
    }

    if (plotBackgroundColor != null) {
        chart.getPlot().setBackgroundPaint(plotBackgroundColor);
    }
    chart.getPlot().setBackgroundAlpha(plotBackgroundAlpha);
    chart.getPlot().setForegroundAlpha(plotForegroundAlpha);
    final Color borderCol = parseColorFromString(getBorderColor());
    if (borderCol != null) {
        chart.setBorderPaint(borderCol);
    }

    //remove legend if showLegend = false
    if (!isShowLegend()) {
        chart.removeLegend();
    } else { //if true format legend
        final LegendTitle chLegend = chart.getLegend();
        if (chLegend != null) {
            final RectangleEdge loc = translateEdge(legendLocation.toLowerCase());
            if (loc != null) {
                chLegend.setPosition(loc);
            }
            if (getLegendFont() != null) {
                chLegend.setItemFont(Font.decode(getLegendFont()));
            }
            if (!isDrawLegendBorder()) {
                chLegend.setBorder(BlockBorder.NONE);
            }
            if (legendBackgroundColor != null) {
                chLegend.setBackgroundPaint(legendBackgroundColor);
            }
            if (legendTextColor != null) {
                chLegend.setItemPaint(legendTextColor);
            }
        }

    }

    final Plot plot = chart.getPlot();
    plot.setNoDataMessageFont(Font.decode(getLabelFont()));

    final String message = getNoDataMessage();
    if (message != null) {
        plot.setNoDataMessage(message);
    }

    plot.setOutlineVisible(isChartSectionOutline());

    if (backgroundImage != null) {
        if (plotImageCache != null) {
            plot.setBackgroundImage(plotImageCache);
        } else {
            final ExpressionRuntime expressionRuntime = getRuntime();
            final ProcessingContext context = expressionRuntime.getProcessingContext();
            final ResourceKey contentBase = context.getContentBase();
            final ResourceManager manager = context.getResourceManager();
            try {
                final ResourceKey key = createKeyFromString(manager, contentBase, backgroundImage);
                final Resource resource = manager.create(key, null, Image.class);
                final Image image = (Image) resource.getResource();
                plot.setBackgroundImage(image);
                plotImageCache = image;
            } catch (Exception e) {
                logger.error("ABSTRACTCHARTEXPRESSION.ERROR_0007_ERROR_RETRIEVING_PLOT_IMAGE", e); //$NON-NLS-1$
                throw new IllegalStateException("Failed to process chart");
            }
        }
    }
}

From source file:net.sf.mzmine.chartbasics.chartthemes.ChartThemeParameters.java

public void applyToChart(JFreeChart chart) {
    // apply chart settings
    boolean showTitle = this.getParameter(ChartThemeParameters.showTitle).getValue();
    boolean changeTitle = this.getParameter(ChartThemeParameters.changeTitle).getValue();
    String title = this.getParameter(ChartThemeParameters.changeTitle).getEmbeddedParameter().getValue();
    boolean showLegends = this.getParameter(ChartThemeParameters.showLegends).getValue();

    boolean usexlabel = this.getParameter(ChartThemeParameters.xlabel).getValue();
    boolean useylabel = this.getParameter(ChartThemeParameters.ylabel).getValue();
    String xlabel = this.getParameter(ChartThemeParameters.xlabel).getEmbeddedParameter().getValue();
    String ylabel = this.getParameter(ChartThemeParameters.ylabel).getEmbeddedParameter().getValue();

    Color gbColor = this.getParameter(ChartThemeParameters.color).getValue();
    chart.setBackgroundPaint(gbColor);/*  w w w. j ava 2s .c  o  m*/
    chart.getPlot().setBackgroundPaint(gbColor);

    if (changeTitle)
        chart.setTitle(title);
    chart.getTitle().setVisible(showTitle);
    ((List<Title>) chart.getSubtitles()).stream().forEach(t -> t.setVisible(showLegends));

    if (chart.getXYPlot() != null) {
        XYPlot p = chart.getXYPlot();
        if (usexlabel)
            p.getDomainAxis().setLabel(xlabel);
        if (useylabel)
            p.getRangeAxis().setLabel(ylabel);

        boolean xgrid = this.getParameter(ChartThemeParameters.xGridPaint).getValue();
        boolean ygrid = this.getParameter(ChartThemeParameters.yGridPaint).getValue();
        Color cxgrid = this.getParameter(ChartThemeParameters.xGridPaint).getEmbeddedParameter().getValue();
        Color cygrid = this.getParameter(ChartThemeParameters.yGridPaint).getEmbeddedParameter().getValue();
        p.setDomainGridlinesVisible(xgrid);
        p.setDomainGridlinePaint(cxgrid);
        p.setRangeGridlinesVisible(ygrid);
        p.setRangeGridlinePaint(cygrid);

        p.getDomainAxis().setVisible(this.getParameter(ChartThemeParameters.showXAxis).getValue());
        p.getRangeAxis().setVisible(this.getParameter(ChartThemeParameters.showYAxis).getValue());
    }
}

From source file:msec.org.Tools.java

public static String generateFullDayChart(String filename, OneDayValue[] data, String title) {
    if (data[0].getValues().length != 1440) {
        return "data size invalid";
    }/*  www.  java2 s  . com*/
    if (data.length > 1) {
        if (data[1].getValues() == null || data[1].getValues().length != 1440) {
            return "data 1 invalid";
        }
    }

    XYDataset xydataset = createDataset(data);
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "time", "", xydataset, true, true, true);

    try {
        XYPlot xyplot = (XYPlot) jfreechart.getPlot();

        //
        DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
        dateaxis.setDateFormatOverride(new SimpleDateFormat("HH:mm"));
        dateaxis.setLabelFont(new Font("", Font.PLAIN, 16)); //
        dateaxis.setLabelPaint(ChartColor.gray);
        dateaxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        dateaxis.setTickLabelPaint(ChartColor.GRAY);

        GregorianCalendar endgc = (GregorianCalendar) gc.clone();
        endgc.add(GregorianCalendar.DATE, 1);
        dateaxis.setMaximumDate(endgc.getTime());

        dateaxis.setTickMarksVisible(true);
        dateaxis.setTickMarkInsideLength(5);
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnitType.HOUR, 2));
        dateaxis.setVerticalTickLabels(true);
        dateaxis.setLabel("");

        //
        ValueAxis rangeAxis = xyplot.getRangeAxis();//?
        rangeAxis.setLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setLabelPaint(ChartColor.gray);
        rangeAxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setTickLabelPaint(ChartColor.gray);
        rangeAxis.setLowerBound(0);

        //
        jfreechart.getLegend().setItemFont(new Font("", Font.PLAIN, 12));
        jfreechart.getLegend().setItemPaint(ChartColor.gray);
        jfreechart.getLegend().setBorder(0, 0, 0, 0);//

        //
        jfreechart.getTitle().setFont(new Font("", Font.PLAIN, 18));//
        jfreechart.getTitle().setPaint(ChartColor.gray);

        //?
        xyplot.setRangeGridlinePaint(ChartColor.GRAY);
        xyplot.setBackgroundPaint(ChartColor.WHITE);
        xyplot.setOutlinePaint(null);//

        int w = 500;
        int h = 300;

        // ChartUtilities.saveChartAsPNG(new File(filename), jfreechart, w, h);
        ChartUtilities.saveChartAsJPEG(new File(filename), 0.8f, jfreechart, w, h);

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}