Example usage for org.jfree.chart JFreeChart getLegend

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

Introduction

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

Prototype

public LegendTitle getLegend() 

Source Link

Document

Returns the legend for the chart, if there is one.

Usage

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

@Override
public void apply(JFreeChart chart) {
    // TODO Auto-generated method stub
    super.apply(chart);
    ///*from w w w . j ava 2 s . c o  m*/
    chart.getXYPlot().setDomainGridlinesVisible(showXGrid);
    chart.getXYPlot().setRangeGridlinesVisible(showYGrid);
    // all axes
    for (int i = 0; i < chart.getXYPlot().getDomainAxisCount(); i++) {
        NumberAxis a = (NumberAxis) chart.getXYPlot().getDomainAxis(i);
        a.setTickMarkPaint(axisLinePaint);
        a.setAxisLinePaint(axisLinePaint);
        // visible?
        a.setVisible(showXAxis);
    }
    for (int i = 0; i < chart.getXYPlot().getRangeAxisCount(); i++) {
        NumberAxis a = (NumberAxis) chart.getXYPlot().getRangeAxis(i);
        a.setTickMarkPaint(axisLinePaint);
        a.setAxisLinePaint(axisLinePaint);
        // visible?
        a.setVisible(showYAxis);
    }
    // apply bg
    chart.setBackgroundPaint(this.getChartBackgroundPaint());
    chart.getPlot().setBackgroundPaint(this.getPlotBackgroundPaint());

    for (int i = 0; i < chart.getSubtitleCount(); i++) {
        // visible?
        chart.getSubtitle(i).setVisible(subtitleVisible);
        //
        if (PaintScaleLegend.class.isAssignableFrom(chart.getSubtitle(i).getClass()))
            ((PaintScaleLegend) chart.getSubtitle(i)).setBackgroundPaint(this.getChartBackgroundPaint());
    }
    if (chart.getLegend() != null)
        chart.getLegend().setBackgroundPaint(this.getChartBackgroundPaint());

    //
    chart.setAntiAlias(isAntiAliased());
    chart.getTitle().setVisible(isShowTitle());
    chart.getPlot().setBackgroundAlpha(isNoBackground() ? 0 : 1);
}

From source file:fr.inria.soctrace.framesoc.ui.piechart.view.StatisticsPieChartView.java

/**
 * Creates the chart./*from  w ww. j  av  a2s .c o  m*/
 * 
 * @param dataset
 *            the dataset.
 * @param loader
 *            the pie chart loader
 * @param dataRequested
 *            flag indicating if the data have been requested for the current loader and the
 *            current interval
 * @return the pie chart
 */
private JFreeChart createChart(PieDataset dataset, String title, IPieChartLoader loader,
        boolean dataRequested) {

    JFreeChart chart = ChartFactory.createPieChart(title, dataset, HAS_LEGEND, HAS_TOOLTIPS, HAS_URLS);

    // legend
    if (HAS_LEGEND) {
        LegendTitle legend = chart.getLegend();
        legend.setPosition(RectangleEdge.LEFT);
    }

    // plot
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setSectionOutlinesVisible(false);
    plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    plot.setNoDataMessage(
            "No data available " + (dataRequested ? "in this time interval" : "yet. Press the Load button."));
    plot.setCircular(true);
    plot.setLabelGenerator(null); // hide labels
    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlineVisible(false);
    plot.setShadowPaint(Color.WHITE);
    plot.setBaseSectionPaint(Color.WHITE);
    StandardPieToolTipGenerator g = (StandardPieToolTipGenerator) plot.getToolTipGenerator();
    NumberFormat format = ValueLabelProvider.getActualFormat(loader.getFormat(), getTimeUnit());
    StandardPieToolTipGenerator sg = new StandardPieToolTipGenerator(g.getLabelFormat(), format,
            g.getPercentFormat());
    plot.setToolTipGenerator(sg);

    for (Object o : dataset.getKeys()) {
        String key = (String) o;
        plot.setSectionPaint(key, loader.getColor(key).getAwtColor());
    }
    return chart;
}

From source file:com.rapidminer.gui.plotter.charts.DeviationChartPlotter.java

@Override
public void updatePlotter() {
    int categoryCount = prepareData();
    String maxClassesProperty = ParameterService
            .getParameterValue(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_COLORS_CLASSLIMIT);
    int maxClasses = 20;
    try {//from w w  w  .ja v a  2 s .c  o m
        if (maxClassesProperty != null) {
            maxClasses = Integer.parseInt(maxClassesProperty);
        }
    } catch (NumberFormatException e) {
        // LogService.getGlobal().log("Deviation plotter: cannot parse property 'rapidminer.gui.plotter.colors.classlimit', using maximal 20 different classes.",
        // LogService.WARNING);
        LogService.getRoot().log(Level.WARNING,
                "com.rapidminer.gui.plotter.charts.DeviationChartPlotter.parsing_property_error");
    }
    boolean createLegend = categoryCount > 0 && categoryCount < maxClasses;

    JFreeChart chart = createChart(this.dataset, createLegend);

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

    // domain axis
    SymbolAxis axis = null;
    if (this.dataTable.isSupportingColumnWeights()) {
        List<Double> weightList = new LinkedList<Double>();
        for (int column = 0; column < dataTable.getNumberOfColumns(); column++) {
            if (!dataTable.isSpecial(column) && column != colorColumn) {
                weightList.add(this.dataTable.getColumnWeight(column));
            }
        }
        double[] weights = new double[weightList.size()];
        int index = 0;
        for (Double d : weightList) {
            weights[index++] = d;
        }
        axis = new WeightBasedSymbolAxis(null, domainAxisMap, weights);
    } else {
        axis = new SymbolAxis(null, domainAxisMap);
    }
    axis.setTickLabelFont(LABEL_FONT);
    axis.setLabelFont(LABEL_FONT_BOLD);

    // rotate labels
    if (isLabelRotating()) {
        axis.setTickLabelsVisible(true);
        axis.setVerticalTickLabels(true);
    }

    chart.getXYPlot().setDomainAxis(axis);

    // legend settings
    LegendTitle legend = chart.getLegend();
    if (legend != null) {
        legend.setPosition(RectangleEdge.TOP);
        legend.setFrame(BlockBorder.NONE);
        legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
        legend.setItemFont(LABEL_FONT);
    }

    if (panel instanceof AbstractChartPanel) {
        panel.setChart(chart);
    } else {
        panel = new AbstractChartPanel(chart, getWidth(), getHeight() - MARGIN);
        final ChartPanelShiftController controller = new ChartPanelShiftController(panel);
        panel.addMouseListener(controller);
        panel.addMouseMotionListener(controller);
    }

    // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!!
    panel.getChartRenderingInfo().setEntityCollection(null);
}

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 .  java 2  s.co 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:mil.tatrc.physiology.utilities.csv.plots.CSVPlotTool.java

public void formatXYPlot(JFreeChart chart, Paint bgColor) {
    XYPlot plot = (XYPlot) chart.getPlot();

    //For Scientific notation
    NumberFormat formatter = new DecimalFormat("0.######E0");

    for (int i = 0; i < plot.getDomainAxisCount(); i++) {
        plot.getDomainAxis(i).setLabelFont(largeFont);
        plot.getDomainAxis(i).setTickLabelFont(smallFont);
        plot.getDomainAxis(i).setLabelPaint(bgColor == Color.red ? Color.white : Color.black);
        plot.getDomainAxis(i).setTickLabelPaint(bgColor == Color.red ? Color.white : Color.black);
    }//from   w ww. j a  v a2 s .com
    for (int i = 0; i < plot.getRangeAxisCount(); i++) {
        plot.getRangeAxis(i).setLabelFont(largeFont);
        plot.getRangeAxis(i).setTickLabelFont(smallFont);
        plot.getRangeAxis(i).setLabelPaint(bgColor == Color.red ? Color.white : Color.black);
        plot.getRangeAxis(i).setTickLabelPaint(bgColor == Color.red ? Color.white : Color.black);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(i);
        rangeAxis.setNumberFormatOverride(formatter);
    }

    //White background outside of plottable area
    chart.setBackgroundPaint(bgColor);

    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinePaint(Color.black);

    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    chart.getLegend().setItemFont(smallFont);
    chart.getTitle().setFont(largeFont);
    chart.getTitle().setPaint(bgColor == Color.red ? Color.white : Color.black);
}

From source file:com.rapidminer.gui.plotter.charts.WebPlotter.java

@Override
public void updatePlotter() {
    final int categoryCount = prepareData();

    SwingUtilities.invokeLater(new Runnable() {

        @Override/*from   w  w w  .j  a v  a 2 s . c o  m*/
        public void run() {
            scrollablePlotterPanel.remove(viewScrollBar);
        }
    });

    if (categoryCount > MAX_CATEGORY_VIEW_COUNT && showScrollbar) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                viewScrollBar.setOrientation(Adjustable.HORIZONTAL);
                scrollablePlotterPanel.add(viewScrollBar, BorderLayout.SOUTH);
            }
        });

        this.slidingCategoryDataSet = new SlidingCategoryDataset(categoryDataSet, 0, MAX_CATEGORY_VIEW_COUNT);
        viewScrollBar.setMaximum(categoryCount);
        viewScrollBar.setValue(0);

    } else {
        this.slidingCategoryDataSet = null;
    }

    if (categoryCount <= MAX_CATEGORIES) {

        SpiderWebPlot plot = new SpiderWebPlot(categoryDataSet);

        plot.setAxisLinePaint(Color.LIGHT_GRAY);
        plot.setOutlinePaint(Color.WHITE);

        plot.setLabelGenerator(new StandardCategoryItemLabelGenerator());

        JFreeChart chart = new JFreeChart("", TextTitle.DEFAULT_FONT, plot, true);

        double[] colorValues = null;
        if (groupByColumn >= 0 && this.dataTable.isNominal(groupByColumn)) {
            colorValues = new double[this.dataTable.getNumberOfValues(groupByColumn)];
        } else {
            colorValues = new double[categoryDataSet.getColumnCount()];
        }
        for (int i = 0; i < colorValues.length; i++) {
            colorValues[i] = i;
        }

        if (panel != null) {
            panel.setChart(chart);
        } else {
            panel = new AbstractChartPanel(chart, getWidth(), getHeight() - MARGIN);
            scrollablePlotterPanel.add(panel, BorderLayout.CENTER);
            final ChartPanelShiftController controller = new ChartPanelShiftController(panel);
            panel.addMouseListener(controller);
            panel.addMouseMotionListener(controller);
        }

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

        // legend settings
        LegendTitle legend = chart.getLegend();
        if (legend != null) {
            legend.setPosition(RectangleEdge.TOP);
            legend.setFrame(BlockBorder.NONE);
            legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
            legend.setItemFont(LABEL_FONT);
        }
        if (groupByColumn < 0) {
            // no legend is needed when there is no group-by selection
            chart.removeLegend();
        }
        // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!!
        panel.getChartRenderingInfo().setEntityCollection(null);
    } else {
        LogService.getRoot().log(Level.INFO,
                "com.rapidminer.gui.plotter.charts.BarChartPlotter.too_many_columns",
                new Object[] { categoryCount, MAX_CATEGORIES });
    }
}

From source file:net.sourceforge.processdash.ui.web.CGIChartBase.java

/** Generate CGI chart output. */
@Override/*  w ww  .ja  va  2s  .co m*/
protected void writeContents() throws IOException {
    buildData(); // get the data for display

    chromeless = (parameters.get("chromeless") != null);
    JFreeChart chart = createChart();

    int width = getIntSetting("width");
    int height = getIntSetting("height");
    Color initGradColor = getColorSetting("initGradColor");
    Color finalGradColor = getColorSetting("finalGradColor");
    chart.setBackgroundPaint(new GradientPaint(0, 0, initGradColor, width, height, finalGradColor));
    if (parameters.get("hideOutline") != null)
        chart.getPlot().setOutlinePaint(INVISIBLE);

    String title = getSetting("title");
    if (chromeless || title == null || title.length() == 0)
        chart.setTitle((TextTitle) null);
    else {
        chart.setTitle(Translator.translate(title));
        String titleFontSize = getSetting("titleFontSize");
        if (titleFontSize != null)
            try {
                float fontSize = Float.parseFloat(titleFontSize);
                TextTitle t = chart.getTitle();
                t.setFont(t.getFont().deriveFont(fontSize));
            } catch (Exception tfe) {
            }
    }

    if (chromeless || parameters.get("hideLegend") != null)
        chart.removeLegend();
    else {
        LegendTitle l = chart.getLegend();
        String legendFontSize = getSetting("legendFontSize");
        if (l != null && legendFontSize != null)
            try {
                float fontSize = Float.parseFloat(legendFontSize);
                l.setItemFont(l.getItemFont().deriveFont(fontSize));
            } catch (Exception lfe) {
            }
    }

    chart.getPlot().setNoDataMessage(resources.getString("No_Data_Message"));

    Axis xAxis = getHorizontalAxis(chart);
    if (xAxis != null) {
        if (parameters.get("hideTickLabels") != null || parameters.get("hideXTickLabels") != null) {
            xAxis.setTickLabelsVisible(false);
        } else if (parameters.get("tickLabelFontSize") != null
                || parameters.get("xTickLabelFontSize") != null) {
            String tfs = getParameter("xTickLabelFontSize");
            if (tfs == null)
                tfs = getParameter("tickLabelFontSize");
            float fontSize = Float.parseFloat(tfs);
            xAxis.setTickLabelFont(xAxis.getTickLabelFont().deriveFont(fontSize));
        }
    }

    Axis yAxis = getVerticalAxis(chart);
    if (yAxis != null) {
        if (parameters.get("hideTickLabels") != null || parameters.get("hideYTickLabels") != null) {
            yAxis.setTickLabelsVisible(false);
        } else if (parameters.get("tickLabelFontSize") != null
                || parameters.get("yTickLabelFontSize") != null) {
            String tfs = getParameter("yTickLabelFontSize");
            if (tfs == null)
                tfs = getParameter("tickLabelFontSize");
            float fontSize = Float.parseFloat(tfs);
            yAxis.setTickLabelFont(yAxis.getTickLabelFont().deriveFont(fontSize));
        }
    }

    String axisFontSize = getSetting("axisLabelFontSize");
    if (axisFontSize != null)
        try {
            float fontSize = Float.parseFloat(axisFontSize);
            if (xAxis != null)
                xAxis.setLabelFont(xAxis.getLabelFont().deriveFont(fontSize));
            if (yAxis != null)
                yAxis.setLabelFont(yAxis.getLabelFont().deriveFont(fontSize));
        } catch (Exception afs) {
        }

    ChartRenderingInfo info = (isHtmlMode() ? new ChartRenderingInfo() : null);
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = img.createGraphics();
    if ("auto".equals(getSetting("titleFontSize")))
        maybeAdjustTitleFontSize(chart, g2, width);
    chart.draw(g2, new Rectangle2D.Double(0, 0, width, height), info);
    g2.dispose();

    String outputFormat = getSetting("outputFormat");
    OutputStream imgOut;
    if (isHtmlMode()) {
        imgOut = PngCache.getOutputStream();
    } else {
        imgOut = outStream;
    }
    ImageIO.write(img, outputFormat, imgOut);
    imgOut.flush();
    imgOut.close();
    if (isHtmlMode())
        writeImageHtml(width, height, imgOut.hashCode(), info);
}

From source file:org.tiefaces.components.websheet.chart.ChartHelper.java

/**
 * finalize the style for jfreechart. The default setting is different from
 * jfreechart and Excel. We try to minimize the difference.
 * /*from   www.  jav  a 2s  . c  o  m*/
 * @param chart
 *            jfreechart.
 * @param chartData
 *            contain information gathered from excel chart object.
 */

private void setupStyle(final JFreeChart chart, final ChartData chartData) {
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    List<ChartSeries> seriesList = chartData.getSeriesList();
    BasicStroke bLine = new BasicStroke(2.0f);
    for (int i = 0; i < seriesList.size(); i++) {
        Color cColor = ColorUtility.xssfClrToClr(seriesList.get(i).getSeriesColor().getXssfColor());
        plot.getRenderer().setSeriesPaint(i, cColor);
        plot.getRenderer().setSeriesStroke(i, bLine);
    }
    plot.setBackgroundPaint(ColorUtility.xssfClrToClr(chartData.getBgColor().getXssfColor()));

    // below are modifications for default setting in excel chart
    // to-do: need read setting from xml in future
    plot.setOutlineVisible(false);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.BLACK);
    plot.setRangeGridlineStroke(new BasicStroke(TieConstants.DEFAULT_BASIC_STROKE));
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
    chart.setBackgroundPaint(Color.WHITE);
    LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.RIGHT);
    legend.setFrame(BlockBorder.NONE);

}

From source file:io.github.mzmine.modules.plots.msspectrum.MsSpectrumPlotWindowController.java

public void initialize() {

    final JFreeChart chart = chartNode.getChart();
    final XYPlot plot = chart.getXYPlot();

    // Do not set colors and strokes dynamically. They are instead provided
    // by the dataset and configured in configureRenderer()
    plot.setDrawingSupplier(null);/*  w w  w  .  j a  v  a2 s .  c  om*/
    plot.setDomainGridlinePaint(JavaFXUtil.convertColorToAWT(gridColor));
    plot.setRangeGridlinePaint(JavaFXUtil.convertColorToAWT(gridColor));
    plot.setBackgroundPaint(JavaFXUtil.convertColorToAWT(backgroundColor));
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);

    // chart properties
    chart.setBackgroundPaint(JavaFXUtil.convertColorToAWT(backgroundColor));

    // legend properties
    LegendTitle legend = chart.getLegend();
    // legend.setItemFont(legendFont);
    legend.setFrame(BlockBorder.NONE);

    // set the X axis (m/z) properties
    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setLabel("m/z");
    xAxis.setUpperMargin(0.03);
    xAxis.setLowerMargin(0.03);
    xAxis.setRangeType(RangeType.POSITIVE);
    xAxis.setTickLabelInsets(new RectangleInsets(0, 0, 20, 20));

    // set the Y axis (intensity) properties
    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setLabel("Intensity");
    yAxis.setRangeType(RangeType.POSITIVE);
    yAxis.setAutoRangeIncludesZero(true);

    // set the fixed number formats, because otherwise JFreeChart sometimes
    // shows exponent, sometimes it doesn't
    DecimalFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    xAxis.setNumberFormatOverride(mzFormat);
    DecimalFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();
    yAxis.setNumberFormatOverride(intensityFormat);

    chartTitle = chartNode.getChart().getTitle();
    chartTitle.setMargin(5, 0, 0, 0);
    chartTitle.setFont(titleFont);

    chartNode.setCursor(Cursor.CROSSHAIR);

    // Remove the dataset if it is removed from the list
    datasets.addListener((Change<? extends MsSpectrumDataSet> c) -> {
        while (c.next()) {
            if (c.wasRemoved()) {
                for (MsSpectrumDataSet ds : c.getRemoved()) {
                    int index = plot.indexOf(ds);
                    plot.setDataset(index, null);
                }
            }
        }
    });

    itemLabelsVisible.addListener((prop, oldVal, newVal) -> {
        for (MsSpectrumDataSet dataset : datasets) {
            int datasetIndex = plot.indexOf(dataset);
            XYItemRenderer renderer = plot.getRenderer(datasetIndex);
            renderer.setBaseItemLabelsVisible(newVal);
        }
    });

    legendVisible.addListener((prop, oldVal, newVal) -> {
        legend.setVisible(newVal);
    });

}

From source file:com.igalia.java.zk.components.JFreeChartEngine.java

public byte[] drawChart(Object data) {
    Chart chart = (Chart) data;// ww w.  j  a  v  a  2 s. co  m
    ChartImpl impl = getChartImpl(chart);
    JFreeChart jfchart = impl.createChart(chart);

    Plot plot = (Plot) jfchart.getPlot();
    float alpha = (float) (((float) chart.getFgAlpha()) / 255);
    plot.setForegroundAlpha(alpha);

    alpha = (float) (((float) chart.getBgAlpha()) / 255);
    plot.setBackgroundAlpha(alpha);

    int[] bgRGB = chart.getBgRGB();
    if (bgRGB != null) {
        plot.setBackgroundPaint(new Color(bgRGB[0], bgRGB[1], bgRGB[2], chart.getBgAlpha()));
    }

    int[] paneRGB = chart.getPaneRGB();
    if (paneRGB != null) {
        jfchart.setBackgroundPaint(new Color(paneRGB[0], paneRGB[1], paneRGB[2], chart.getPaneAlpha()));
    }

    //since 3.6.3, JFreeChart 1.0.13 change default fonts which does not support Chinese, allow
    //developer to set font.

    //title font
    final Font tfont = chart.getTitleFont();
    if (tfont != null) {
        jfchart.getTitle().setFont(tfont);
    }

    //legend font
    final Font lfont = chart.getLegendFont();
    if (lfont != null) {
        jfchart.getLegend().setItemFont(lfont);
    }

    if (plot instanceof CategoryPlot) {
        final CategoryPlot cplot = (CategoryPlot) plot;
        cplot.setRangeGridlinePaint(new Color(0xc0, 0xc0, 0xc0));

        //Domain axis(x axis)
        final Font xlbfont = chart.getXAxisFont();
        final Font xtkfont = chart.getXAxisTickFont();
        if (xlbfont != null) {
            cplot.getDomainAxis().setLabelFont(xlbfont);
        }
        if (xtkfont != null) {
            cplot.getDomainAxis().setTickLabelFont(xtkfont);
        }

        Color[] colorMappings = (Color[]) chart.getAttribute("series-color-mappings");
        if (colorMappings != null) {
            for (int ii = 0; ii < colorMappings.length; ii++) {
                cplot.getRenderer().setSeriesPaint(ii, colorMappings[ii]);
            }
        }

        Double lowerBound = (Double) chart.getAttribute("range-axis-lower-bound");
        if (lowerBound != null) {
            cplot.getRangeAxis().setAutoRange(false);
            cplot.getRangeAxis().setLowerBound(lowerBound);
        }

        Double upperBound = (Double) chart.getAttribute("range-axis-upper-bound");
        if (upperBound != null) {
            cplot.getRangeAxis().setAutoRange(false);
            cplot.getRangeAxis().setUpperBound(upperBound);
        }

        //Range axis(y axis)
        final Font ylbfont = chart.getYAxisFont();
        final Font ytkfont = chart.getYAxisTickFont();
        if (ylbfont != null) {
            cplot.getRangeAxis().setLabelFont(ylbfont);
        }
        if (ytkfont != null) {
            cplot.getRangeAxis().setTickLabelFont(ytkfont);
        }
    } else if (plot instanceof XYPlot) {
        final XYPlot xyplot = (XYPlot) plot;
        xyplot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        xyplot.setDomainGridlinePaint(Color.LIGHT_GRAY);

        //Domain axis(x axis)
        final Font xlbfont = chart.getXAxisFont();
        final Font xtkfont = chart.getXAxisTickFont();
        if (xlbfont != null) {
            xyplot.getDomainAxis().setLabelFont(xlbfont);
        }
        if (xtkfont != null) {
            xyplot.getDomainAxis().setTickLabelFont(xtkfont);
        }

        //Range axis(y axis)
        final Font ylbfont = chart.getYAxisFont();
        final Font ytkfont = chart.getYAxisTickFont();
        if (ylbfont != null) {
            xyplot.getRangeAxis().setLabelFont(ylbfont);
        }
        if (ytkfont != null) {
            xyplot.getRangeAxis().setTickLabelFont(ytkfont);
        }
    } else if (plot instanceof PiePlot) {
        plot.setOutlineStroke(null);
    }

    //callbacks for each area
    ChartRenderingInfo jfinfo = new ChartRenderingInfo();
    BufferedImage bi = jfchart.createBufferedImage(chart.getIntWidth(), chart.getIntHeight(),
            Transparency.TRANSLUCENT, jfinfo);

    //remove old areas
    if (chart.getChildren().size() > 20)
        chart.invalidate(); //improve performance if too many chart
    chart.getChildren().clear();

    if (Events.isListened(chart, Events.ON_CLICK, false) || chart.isShowTooltiptext()) {
        int j = 0;
        String preUrl = null;
        for (Iterator it = jfinfo.getEntityCollection().iterator(); it.hasNext();) {
            ChartEntity ce = (ChartEntity) it.next();
            final String url = ce.getURLText();

            //workaround JFreeChart's bug (skip replicate areas)
            if (url != null) {
                if (preUrl == null) {
                    preUrl = url;
                } else if (url.equals(preUrl)) { //start replicate, skip
                    break;
                }
            }

            //1. JFreeChartEntity area cover the whole chart, will "mask" other areas
            //2. LegendTitle area cover the whole legend, will "mask" each legend
            //3. PlotEntity cover the whole chart plotting araa, will "mask" each bar/line/area
            if (!(ce instanceof JFreeChartEntity)
                    && !(ce instanceof TitleEntity && ((TitleEntity) ce).getTitle() instanceof LegendTitle)
                    && !(ce instanceof PlotEntity)) {
                Area area = new Area();
                area.setParent(chart);
                area.setCoords(ce.getShapeCoords());
                area.setShape(ce.getShapeType());
                area.setId("area_" + chart.getId() + '_' + (j++));
                if (chart.isShowTooltiptext() && ce.getToolTipText() != null) {
                    area.setTooltiptext(ce.getToolTipText());
                }
                area.setAttribute("url", ce.getURLText());
                impl.render(chart, area, ce);
                if (chart.getAreaListener() != null) {
                    try {
                        chart.getAreaListener().onRender(area, ce);
                    } catch (Exception ex) {
                        throw UiException.Aide.wrap(ex);
                    }
                }
            }
        }
    }
    //clean up the "LEGEND_SEQ"
    //used for workaround LegendItemEntity.getSeries() always return 0
    //used for workaround TickLabelEntity no information
    chart.removeAttribute("LEGEND_SEQ");
    chart.removeAttribute("TICK_SEQ");

    try {
        //encode into png image format byte array
        return EncoderUtil.encode(bi, ImageFormat.PNG, true);
    } catch (java.io.IOException ex) {
        throw UiException.Aide.wrap(ex);
    }
}