Example usage for java.awt.geom Rectangle2D getWidth

List of usage examples for java.awt.geom Rectangle2D getWidth

Introduction

In this page you can find the example usage for java.awt.geom Rectangle2D getWidth.

Prototype

public abstract double getWidth();

Source Link

Document

Returns the width of the framing rectangle in double precision.

Usage

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.link_and_brush.LinkAndBrushChartPanel.java

@Override
public void mouseReleased(MouseEvent e) {

    // if we've been panning, we need to reset now that the mouse is
    // released...
    Rectangle2D zoomRectangle = (Rectangle2D) getChartFieldValueByName("zoomRectangle");
    Point2D zoomPoint = (Point2D) getChartFieldValueByName("zoomPoint");
    if (getChartFieldValueByName("panLast") != null) {
        setChartFieldValue((getChartFieldByName("panLast")), null);
        setCursor(Cursor.getDefaultCursor());
    } else if (zoomRectangle != null) {
        boolean hZoom = false;
        boolean vZoom = false;
        if ((PlotOrientation) getChartFieldValueByName("orientation") == PlotOrientation.HORIZONTAL) {
            hZoom = (Boolean) getChartFieldValueByName("rangeZoomable");
            vZoom = (Boolean) getChartFieldValueByName("domainZoomable");
        } else {//from  w  w  w  . java  2s  . c  om
            hZoom = (Boolean) getChartFieldValueByName("domainZoomable");
            vZoom = (Boolean) getChartFieldValueByName("rangeZoomable");
        }

        boolean zoomTrigger1 = hZoom && Math
                .abs(e.getX() - zoomPoint.getX()) >= (Integer) getChartFieldValueByName("zoomTriggerDistance");
        boolean zoomTrigger2 = vZoom && Math
                .abs(e.getY() - zoomPoint.getY()) >= (Integer) getChartFieldValueByName("zoomTriggerDistance");
        if (zoomTrigger1 || zoomTrigger2) {
            if ((hZoom && (e.getX() < zoomPoint.getX())) || (vZoom && (e.getY() < zoomPoint.getY()))) {
                restoreAutoBounds();
            } else {
                double x, y, w, h;
                Rectangle2D screenDataArea = getScreenDataArea((int) zoomPoint.getX(), (int) zoomPoint.getY());
                double maxX = screenDataArea.getMaxX();
                double maxY = screenDataArea.getMaxY();
                // for mouseReleased event, (horizontalZoom || verticalZoom)
                // will be true, so we can just test for either being false;
                // otherwise both are true
                if (!vZoom) {
                    x = zoomPoint.getX();
                    y = screenDataArea.getMinY();
                    w = Math.min(zoomRectangle.getWidth(), maxX - zoomPoint.getX());
                    h = screenDataArea.getHeight();
                } else if (!hZoom) {
                    x = screenDataArea.getMinX();
                    y = zoomPoint.getY();
                    w = screenDataArea.getWidth();
                    h = Math.min(zoomRectangle.getHeight(), maxY - zoomPoint.getY());
                } else {
                    x = zoomPoint.getX();
                    y = zoomPoint.getY();
                    w = Math.min(zoomRectangle.getWidth(), maxX - zoomPoint.getX());
                    h = Math.min(zoomRectangle.getHeight(), maxY - zoomPoint.getY());
                }
                Rectangle2D zoomArea = new Rectangle2D.Double(x, y, w, h);
                zoom(zoomArea);
            }
            setChartFieldValue(getChartFieldByName("zoomPoint"), null);
            setChartFieldValue(getChartFieldByName("zoomRectangle"), null);
        } else {
            // erase the zoom rectangle
            Graphics2D g2 = (Graphics2D) getGraphics();
            if ((Boolean) getChartFieldValueByName("useBuffer")) {
                repaint();
            } else {
                drawZoomRectangle(g2, true);
            }
            g2.dispose();
            setChartFieldValue(getChartFieldByName("zoomPoint"), null);
            setChartFieldValue(getChartFieldByName("zoomRectangle"), null);
        }

    }

    else if (e.isPopupTrigger()) {
        if (getChartFieldValueByName("popup") != null) {
            displayPopupMenu(e.getX(), e.getY());
        }
    }

}

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

/***********************************************************************************************
 * Create or refresh the Chart on a separate thread.
 * Only create or update if asked to do so via the generate flag.
 *
 * @param dao// w  ww.j  a  v a  2 s.c  o m
 * @param generateflag
 * @param message
 */

private synchronized void doRefreshChart(final ObservatoryInstrumentDAOInterface dao,
        final boolean generateflag, final String message) {
    //final String SOURCE = "ChartUIComponent.refreshChart() ";
    final String SOURCE = message;
    final ChartUIComponentPlugin thisUI;
    final boolean boolDebug;

    boolDebug = true;
    //        boolDebug = LOADER_PROPERTIES.isMetadataDebug()
    //                    || LOADER_PROPERTIES.isChartDebug();

    // For use in inner classes
    thisUI = this;

    // Stop any existing SwingWorker
    if ((getHostInstrument() != null) && (dao != null)) {
        LOGGER.debug(boolDebug, SOURCE + "DAO [dao.classname=" + dao.getClass().getName()
                + "] [instrument.name=" + dao.getInstrumentName() + "] [generate.flag=" + generateflag + "]");

        LOGGER.debug(boolDebug, SOURCE + "SwingWorker.controlledStop()");
    }

    SwingWorker.disposeWorker(workerRefresh, true, SWING_WORKER_STOP_DELAY >> 1);

    // Fire off another thread to process the Chart
    workerRefresh = new SwingWorker(REGISTRY.getThreadGroup(), SOURCE + "SwingWorker [group="
            + REGISTRY.getThreadGroup().getName() + "] [thread=" + getChartName() + "]") {
        public Object construct() {
            LOGGER.debug(boolDebug, SOURCE
                    + "SwingWorker START -------------------------------------------------------------------------!");

            // The result of this Thread is a JFreeChart
            // which may have been produced in a long process...
            if ((!isStopping()) && (getHostInstrument() != null)
                    && (getHostInstrument().getInstrumentState().isOn())) {
                try {
                    final JFreeChart chart;
                    final Calendar calObservatory;

                    // Either find the Current Observatory calendar, or provide a default
                    calObservatory = ObservatoryInstrumentHelper
                            .getCurrentObservatoryCalendar(REGISTRY.getFramework(), dao, boolDebug);

                    //-----------------------------------------------------------------------------
                    // Debug the data we are trying to display

                    if (boolDebug) {
                        // Dump the (partial) contents of each Series in the composite XYdataset
                        ChartHelper.dumpXYDataset(boolDebug, calObservatory, getPrimaryXYDataset(), 4, SOURCE
                                + "Original unmodified Primary XYDataset before channel or domain selection");

                        if ((getSecondaryXYDatasets() != null) && (!getSecondaryXYDatasets().isEmpty())) {
                            for (int intDatasetIndex = 0; intDatasetIndex < getSecondaryXYDatasets()
                                    .size(); intDatasetIndex++) {
                                ChartHelper.dumpXYDataset(boolDebug, calObservatory,
                                        getSecondaryXYDatasets().get(intDatasetIndex), 4,
                                        SOURCE + "Original unmodified Secondary XYDataset [" + intDatasetIndex
                                                + "] before channel or domain selection");
                            }
                        } else {
                            LOGGER.debug(boolDebug,
                                    SOURCE + "There are no SecondaryXYDatasets associated with this Chart");
                        }
                    }

                    //-----------------------------------------------------------------------------
                    // Apply a ChartUI and its Metadata to the specified DAO

                    ChartHelper.associateChartUIWithDAO(thisUI, getMetadata(), dao);

                    //-----------------------------------------------------------------------------
                    // Create a new Channel Selector showing the channels of the Primary Dataset

                    if ((getChannelSelectorOccupant() != null)
                            && (getHostInstrument().getInstrumentState().isOn()) && (dao != null)
                            && (generateflag)) {
                        LOGGER.debug(boolDebug,
                                SOURCE + "SwingWorker --> ChannelSelector --> createOrUpdateSelectors()");

                        // The Channel Selector will be empty until an XYDataset is loaded
                        // Note that ChannelCount etc. must be set before calling createOrUpdateSelectors()
                        getChannelSelectorOccupant().setChannelCount(getChannelCount());
                        getChannelSelectorOccupant().setTemperatureChannel(hasTemperatureChannel());
                        getChannelSelectorOccupant().setMetadata(getMetadata());
                        getChannelSelectorOccupant().setUpdateType(getUpdateType());

                        // Force a rebuild of the Channel Selector only if necessary
                        getChannelSelectorOccupant().createOrUpdateSelectors(getDatasetType(),
                                getPrimaryXYDataset(), getSecondaryXYDatasets(), dao.isDatasetTypeChanged(),
                                dao.isChannelCountChanged(), dao.isMetadataChanged(), dao.isRawDataChanged(),
                                dao.isProcessedDataChanged(), isRefreshable(), isClickRefresh(), boolDebug);
                    } else {
                        // This debug ASSUMES the Instrument is not NULL
                        LOGGER.debug(boolDebug, SOURCE + "Unable to configure the Channel Selector UIComponent"
                                + "  [has.channelselector=" + (hasChannelSelector())
                                + "] [channelselector.notnull=" + (getChannelSelectorOccupant() != null)
                                + "] [isselectedinstrument="
                                + ObservatoryUIHelper.isSelectedInstrument(getHostInstrument())
                                + "] [isinstrument.on=" + getHostInstrument().getInstrumentState().isOn()
                                + "] [dao.notnull=" + (dao != null) + "] [generateflag=" + generateflag + "]");
                    }

                    //-----------------------------------------------------------------------------
                    // Force a rebuild of the DatasetDomain Control only if necessary

                    if ((hasDatasetDomainControl()) && (getDatasetDomainControlOccupant() != null)
                            && (getHostInstrument().getInstrumentState().isOn()) && (dao != null)
                            && (generateflag)) {
                        LOGGER.debug(boolDebug, SOURCE
                                + "SwingWorker --> DatasetDomainControl --> createOrUpdateDomainControl()");

                        // Note that ChannelCount etc. must be set before calling createOrUpdateDomainControl()
                        getDatasetDomainControlOccupant().setRawDataChannelCount(getChannelCount());
                        getDatasetDomainControlOccupant().setTemperatureChannel(hasTemperatureChannel());
                        getDatasetDomainControlOccupant().setMetadata(getMetadata());
                        getDatasetDomainControlOccupant().setUpdateType(getUpdateType());

                        getDatasetDomainControlOccupant().createOrUpdateDomainControl(getDatasetType(),
                                getPrimaryXYDataset(), getSecondaryXYDatasets(), dao.isDatasetTypeChanged(),
                                dao.isChannelCountChanged(), dao.isMetadataChanged(), dao.isRawDataChanged(),
                                dao.isProcessedDataChanged(), isRefreshable(), isClickRefresh(), boolDebug);
                    } else {
                        // This debug ASSUMES the Instrument is not NULL
                        LOGGER.debug(boolDebug, SOURCE
                                + "Unable to configure the DatasetDomainControl UIComponent"
                                + "  [has.domaincontrol=" + (hasDatasetDomainControl())
                                + "] [domaincontrol.notnull=" + (getDatasetDomainControlOccupant() != null)
                                + "] [isselectedinstrument="
                                + ObservatoryUIHelper.isSelectedInstrument(getHostInstrument())
                                + "] [isinstrument.on=" + getHostInstrument().getInstrumentState().isOn()
                                + "] [dao.notnull=" + (dao != null) + "] [generateflag=" + generateflag + "]");
                    }

                    // Do this anyway, because it doesn't affect the UI
                    updateSliderLocalValues();

                    //-----------------------------------------------------------------------------
                    // If the Chart does not exist, create it
                    // If the Chart structure has changed, recreate it using the new configuration
                    // If only the data have changed, update the existing JFreeChart
                    // and return NULL here, to avoid redrawing

                    LOGGER.debug(boolDebug, SOURCE + "SwingWorker --> createOrUpdateChart()");

                    // Use the Observatory ResourceKey
                    setDisplayLimit(
                            REGISTRY.getIntegerProperty(getHostInstrument().getHostAtom().getResourceKey()
                                    + ResourceKeys.KEY_DISPLAY_DATA_MAX));

                    // Only create or update if asked to do so
                    // This is the last step, so can reset the DAO changed status flags
                    chart = ChartHelper.createOrUpdateChart(getHostInstrument(), thisUI, dao, generateflag,
                            getDatasetType(), getPrimaryXYDataset(), getSecondaryXYDatasets(), getUpdateType(),
                            isRefreshable(), isClickRefresh(), getDisplayLimit(), getDatasetDomainStartPoint(),
                            getDatasetDomainEndPoint(), getChannelSelectorOccupant(), boolDebug);
                    return (chart);
                }

                catch (final Exception exception) {
                    LOGGER.debug(boolDebug, SOURCE + "SwingWorker Thread GENERIC EXCEPTION");
                    exception.printStackTrace();
                    return null;
                }
            } else {
                LOGGER.debug(boolDebug,
                        SOURCE + "SwingWorker Thread stopping, or the Instrument has been turned OFF...");
                return (null);
            }
        }

        // Return a JFreeChart or NULL, depending on the outcome of createOrUpdateChart()
        // If NULL, don't affect the ChartPanel contents
        public void finished() {
            MetadataHelper.showMetadataList(getMetadata(), SOURCE + "Chart Metadata on arrival at finished()",
                    boolDebug);

            // Update the Chart on the Event Dispatching Thread
            // Check thoroughly that there is some point to this update...
            if ((workerRefresh != null) && (workerRefresh.get() != null)
                    && (workerRefresh.get() instanceof JFreeChart) && (SwingUtilities.isEventDispatchThread())
                    && (!isStopping()) && (getHostInstrument() != null)
                    && (getHostInstrument().getInstrumentState().isOn())) {
                // See if we already have a ChartPanel to hold the new JFreeChart
                if (getChartPanel() != null) {
                    LOGGER.debug(boolDebug, SOURCE
                            + "finished() Apply the JFreeChart returned by get() to exisiting ChartPanel");

                    getChartPanel().setChart((JFreeChart) workerRefresh.get());
                } else {
                    // There is NO ChartPanel, so start again from scratch
                    LOGGER.debug(boolDebug, SOURCE
                            + "finished() Create a NEW ChartPanel and apply the JFreeChart returned by get()");

                    setChartPanel(ChartPanelFactory.createChartPanel((JFreeChart) workerRefresh.get()));
                }

                // NOTE: Chart applied to the specified DAO which was passed as a parameter
                LOGGER.debug(boolDebug, SOURCE + "finished() returned JFreeChart on a ChartPanel");

                getChartContainer().removeAll();
                getChartContainer().add(getChartPanel(), BorderLayout.CENTER);
                getChartPanel().getChart().fireChartChanged();
                getChartContainer().revalidate();
            } else {
                // We failed to return a JFreeChart for some reason

                if (getPrimaryXYDataset() == null) {
                    LOGGER.debug(boolDebug, SOURCE
                            + "finished() No JFreeChart returned, Dataset is NULL, show BlankUIComponent");

                    // Getting here with a NULL dataset should mean no Chart!
                    // ChartContainer is always NOT NULL
                    getChartContainer().removeAll();
                    getChartContainer().add(
                            new BlankUIComponent(MSG_WAITING_FOR_DATA, DEFAULT_COLOUR_CANVAS, COLOUR_INFO_TEXT),
                            BorderLayout.CENTER);
                    getChartContainer().revalidate();

                    // ToDo Consider setting DAO Chart and ChartPanel Chart to NULL?
                    //SOURCE + "finished() No JFreeChart returned, Dataset is NULL, set Chart to NULL if possible");

                    //                        if (getChartPanel() != null)
                    //                            {
                    //                            getChartPanel().setChart(null);
                    //                            }
                } else {
                    // We have some data, if we also have a Chart, just display it again
                    if ((getChartPanel() != null) && (getChartPanel().getChart() != null)) {
                        LOGGER.debug(boolDebug, SOURCE
                                + "finished() No JFreeChart returned, Dataset is NOT NULL, redraw data on existing ChartPanel");

                        getChartContainer().removeAll();
                        getChartContainer().add(getChartPanel(), BorderLayout.CENTER);
                        getChartPanel().getChart().fireChartChanged();
                        getChartContainer().revalidate();
                    } else {
                        LOGGER.error(SOURCE
                                + "finished() No JFreeChart returned, Dataset is NOT NULL, but no Chart for display, no action taken");
                    }
                }
            }

            // Handle the DatasetDomainControl

            if ((getChartPanel() != null) && (hasDatasetDomainControl())
                    && (getDatasetDomainControlOccupant() != null)
                    && (getDatasetDomainControlOccupant().getDatasetDomainContainer() != null)) {
                final ChartRenderingInfo infoChart;
                final PlotRenderingInfo infoPlot;
                final Rectangle2D rectPlot;
                final Rectangle2D rectData;

                infoChart = getChartPanel().getChartRenderingInfo();
                infoPlot = infoChart.getPlotInfo();
                rectPlot = infoPlot.getPlotArea();
                rectData = infoPlot.getDataArea();

                // Trap the cases where the Plot hasn't been rendered, or there's nothing to lay out,
                // in which cases use the default sizes
                if ((rectPlot != null) && (rectData != null) && ((int) rectData.getWidth() > 0)
                        && ((int) rectData.getHeight() > 0) && ((int) rectData.getX() > 0)
                        && ((int) rectData.getY() > 0)) {
                    int intLeft;
                    int intRight;

                    // Try to get the slider to align with the extents of the data area
                    // Ideally this should happen also after WindowResizing events
                    intLeft = (int) rectData.getX();
                    intRight = (int) (getChartPanel().getWidth() - rectData.getWidth() - rectData.getX());

                    LOGGER.debug(boolDebug,
                            "DatasetDomainControl -- PANEL, PLOT & DATA AREAS" + "  [panel.width="
                                    + getChartPanel().getWidth() + "] [panel.height="
                                    + getChartPanel().getHeight() + "] [plot.width=" + rectPlot.getWidth()
                                    + "] [plot.height=" + rectPlot.getHeight() + "] [plot.x=" + rectPlot.getX()
                                    + "] [plot.y=" + rectPlot.getY() + "] [data.width=" + rectData.getWidth()
                                    + "] [data.height=" + rectData.getHeight() + "] [data.x=" + rectData.getX()
                                    + "] [data.y=" + rectData.getY() + "] [indent.left=" + intLeft
                                    + "] [indent.right=" + intRight + "]");

                    if (intLeft < 0) {
                        intLeft = 0;
                    }

                    if (intRight < 0) {
                        intRight = 0;
                    }

                    if ((intLeft + rectData.getWidth() + intRight) > getChartPanel().getWidth()) {
                        intRight = 5;
                    }

                    getDatasetDomainControlOccupant().getDatasetDomainContainer()
                            .setBorder(BorderFactory.createEmptyBorder(0, intLeft, 5, intRight));
                } else {
                    getDatasetDomainControlOccupant().getDatasetDomainContainer()
                            .setBorder(BorderFactory.createEmptyBorder(0, INDENT_LEFT, 5, INDENT_RIGHT));
                }

                // Layout the Domain slider control again
                getDatasetDomainControlOccupant().getDatasetDomainContainer().revalidate();
            }

            LOGGER.debug(boolDebug, SOURCE
                    + "SwingWorker.finished() STOP ---------------------------------------------------------------!\n");
        }
    };

    // Start the Thread we have prepared...
    workerRefresh.start();
}

From source file:knop.psfj.BeadImage.java

/**
 * Gets the bead preview.//  w w w  .j  av  a2s .c  o m
 *
 * @param trials the trials
 * @return the bead preview
 */
public ImageProcessor getBeadPreview(int trials) {
    if (trials == 0) {
        return null;
    }
    if (preview == null) {
        try {
            System.out.println("generating new preview");

            preview = getMiddleImage();

            if (preview == null) {
                return new ShortProcessor(previewWidth, previewHeight);
            }

            preview = preview.convertToRGB();

            for (BeadFrame frame : getBeadFrameList()) {
                Rectangle2D r = frame.getBoundaries();

                if (frame.isValid() == true) {
                    preview.setColor(Color.green);
                } else {
                    preview.setColor(Color.yellow);
                }

                if (frame.isValid() == false) {
                    r = getEnlargedFrame((Rectangle) r, MathUtils.round(r.getWidth() / 2));
                }

                preview.drawRect(round(r.getX()), round(r.getY()), round(r.getWidth()), round(r.getHeight()));
                if (frame.getId() == null) {
                    continue;
                }

            }

            status = "Done.";
            progress = 100;

            notifyObservers(MSG_PREVIEW_UPDATED, "Done.", 100, null);
        } catch (Exception e) {
            trials--;
            getBeadPreview(trials);
        }
    }
    return preview;

}

From source file:genlab.gui.jfreechart.EnhancedSpiderWebPlot.java

/**
 * Draws the plot on a Java 2D graphics device (such as the screen or a
 * printer).//from w w  w .ja  v  a  2 s  .  c o m
 *
 * @param g2  the graphics device.
 * @param area  the area within which the plot should be drawn.
 * @param anchor  the anchor point (<code>null</code> permitted).
 * @param parentState  the state from the parent plot, if there is one.
 * @param info  collects info about the drawing.
 */
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {

    // adjust for insets...
    RectangleInsets insets = getInsets();
    insets.trim(area);

    if (info != null) {
        info.setPlotArea(area);
        info.setDataArea(area);
    }

    drawBackground(g2, area);
    //drawOutline(g2, area);

    Shape savedClip = g2.getClip();

    g2.clip(area);
    Composite originalComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));

    if (!DatasetUtilities.isEmptyOrNull(this.dataset)) {
        int seriesCount = 0, catCount = 0;

        if (this.dataExtractOrder == TableOrder.BY_ROW) {
            seriesCount = this.dataset.getRowCount();
            catCount = this.dataset.getColumnCount();
        } else {
            seriesCount = this.dataset.getColumnCount();
            catCount = this.dataset.getRowCount();
        }

        // ensure we have a maximum value to use on the axes
        if (this.maxValue == DEFAULT_MAX_VALUE)
            calculateMaxValue(seriesCount, catCount);

        // Next, setup the plot area

        // adjust the plot area by the interior spacing value

        double gapHorizontal = area.getWidth() * getInteriorGap();
        double gapVertical = area.getHeight() * getInteriorGap();

        double X = area.getX() + gapHorizontal / 2;
        double Y = area.getY() + gapVertical / 2;
        double W = area.getWidth() - gapHorizontal;
        double H = area.getHeight() - gapVertical;

        double headW = area.getWidth() * this.headPercent;
        double headH = area.getHeight() * this.headPercent;

        // make the chart area a square
        double min = Math.min(W, H) / 2;
        X = (X + X + W) / 2 - min;
        Y = (Y + Y + H) / 2 - min;
        W = 2 * min;
        H = 2 * min;

        Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2);
        Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H);

        // draw the axis and category label
        for (int cat = 0; cat < catCount; cat++) {
            double angle = getStartAngle()
                    + (getDirection().getFactor() * cat * 360 / (catCount > 2 ? catCount : 3));

            Point2D endPoint = getWebPoint(radarArea, angle, 1);
            // 1 = end of axis
            Line2D line = new Line2D.Double(centre, endPoint);
            g2.setPaint(this.axisLinePaint);
            g2.setStroke(this.axisLineStroke);
            g2.draw(line);
            drawLabel(g2, radarArea, 0.0, cat, angle, 360.0 / (catCount > 2 ? catCount : 3));
        }

        // Now actually plot each of the series polygons..
        for (int series = 0; series < seriesCount; series++) {
            drawRadarPoly(g2, radarArea, centre, info, series, catCount, headH, headW);
        }
    } else {
        drawNoDataMessage(g2, area);
    }
    g2.setClip(savedClip);
    g2.setComposite(originalComposite);
    //drawOutline(g2, area);
}

From source file:org.rdv.viz.chart.ChartPanel.java

/**
 * Zooms in on a selected region./*from   w ww  . j  av a2 s. c  o m*/
 *
 * @param selection  the selected region.
 */
public void zoom(Rectangle2D selection) {

    // get the origin of the zoom selection in the Java2D space used for
    // drawing the chart (that is, before any scaling to fit the panel)
    Point2D selectOrigin = translateScreenToJava2D(
            new Point((int) Math.ceil(selection.getX()), (int) Math.ceil(selection.getY())));
    PlotRenderingInfo plotInfo = this.info.getPlotInfo();
    Rectangle2D scaledDataArea = getScreenDataArea((int) selection.getCenterX(), (int) selection.getCenterY());
    if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) {

        double hLower = (selection.getMinX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth();
        double hUpper = (selection.getMaxX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth();
        double vLower = (scaledDataArea.getMaxY() - selection.getMaxY()) / scaledDataArea.getHeight();
        double vUpper = (scaledDataArea.getMaxY() - selection.getMinY()) / scaledDataArea.getHeight();

        Plot p = this.chart.getPlot();
        if (p instanceof Zoomable) {
            // save previous ranges for use later when zooming out
            if (p instanceof XYPlot && rangeHistory.empty()) {
                XYPlot xyPlot = (XYPlot) p;
                rangeHistory.push(xyPlot.getDomainAxis().getRange());
                rangeHistory.push(xyPlot.getRangeAxis().getRange());
            }

            Zoomable z = (Zoomable) p;
            if (z.getOrientation() == PlotOrientation.HORIZONTAL) {
                z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin);
                z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin);
            } else {
                z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin);
                z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin);
            }

            // save current ranges for use later when zooming out
            if (p instanceof XYPlot) {
                XYPlot xyPlot = (XYPlot) p;
                rangeHistory.push(xyPlot.getDomainAxis().getRange());
                rangeHistory.push(xyPlot.getRangeAxis().getRange());
            }
        }

    }

}

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

/**
 * Applies any scaling that is in effect for the chart drawing to the given rectangle.
 * //w w w  .  ja  v a 2s  .c  o  m
 * @param rect
 *            the rectangle (<code>null</code> not permitted).
 * 
 * @return A new scaled rectangle.
 */

@Override
public Rectangle2D scale(Rectangle2D rect) {
    Insets insets = getInsets();
    double x = rect.getX() * getScaleX() + insets.left;
    double y = rect.getY() * getScaleY() + insets.top;
    double w = rect.getWidth() * getScaleX();
    double h = rect.getHeight() * getScaleY();
    return new Rectangle2D.Double(x, y, w, h);
}

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

/**
 * Creates a bubble chart with default settings. The chart is composed of an {@link XYPlot}, with a {@link NumberAxis} for the
 * domain axis, a {@link NumberAxis} for the range axis, and an {@link XYBubbleRenderer} to draw the data items.
 * /*from  ww  w .  j  av  a2  s .c  o m*/
 * This method is copied from
 * {@link org.jfree.chart.ChartFactory#createBubbleChart(String, String, String, XYZDataset, PlotOrientation, boolean, boolean, boolean)}
 * 
 * @param title the chart title (<code>null</code> permitted).
 * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
 * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
 * @param dataset the dataset for the chart (<code>null</code> permitted).
 * @param orientation the orientation (horizontal or vertical) (<code>null</code> NOT permitted).
 * @param legend a flag specifying whether or not a legend is required.
 * @param tooltips configure chart to generate tool tips?
 * @param urls configure chart to generate URLs?
 * 
 * @return A bubble chart.
 */
public static JFreeChart createBubbleChart(String title, String xAxisLabel, String yAxisLabel,
        XYZDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) {

    if (orientation == null) {
        throw new IllegalArgumentException(Messages.getString("TopChartFactory.argument")); //$NON-NLS-1$
    }
    NumberAxis xAxis = new NumberAxis(xAxisLabel);
    xAxis.setAutoRangeIncludesZero(false);
    NumberAxis yAxis = new NumberAxis(yAxisLabel);
    yAxis.setAutoRangeIncludesZero(false);

    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);

    XYItemRenderer renderer = new XYBubbleRenderer(XYBubbleRenderer.SCALE_ON_RANGE_AXIS) {

        @Override
        public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
                PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
                XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) {

            // return straight away if the item is not visible
            if (!getItemVisible(series, item)) {
                return;
            }

            PlotOrientation orientation = plot.getOrientation();

            // get the data point...
            double x = dataset.getXValue(series, item);
            double y = dataset.getYValue(series, item);
            double z = Double.NaN;
            if (dataset instanceof XYZDataset) {
                XYZDataset xyzData = (XYZDataset) dataset;
                z = xyzData.getZValue(series, item);
            }
            if (!Double.isNaN(z)) {
                RectangleEdge domainAxisLocation = plot.getDomainAxisEdge();
                RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge();
                double transX = domainAxis.valueToJava2D(x, dataArea, domainAxisLocation);
                double transY = rangeAxis.valueToJava2D(y, dataArea, rangeAxisLocation);

                double transDomain = 0.0;
                double transRange = 0.0;
                double zero;

                // MOD scorreia +2L avoid points: minimal size of circle must be 1
                // z = z * transX + 1;

                // ADD xqliu 2009-07-06 bug 8035
                double zSize = getBubbleSize(z); // calculate the multiple of bubble's default size
                z = 0; // use bubble's default size
                // ~

                switch (getScaleType()) {
                case SCALE_ON_DOMAIN_AXIS:
                    zero = domainAxis.valueToJava2D(0.0, dataArea, domainAxisLocation);
                    transDomain = domainAxis.valueToJava2D(z, dataArea, domainAxisLocation) - zero;
                    transRange = transDomain;
                    break;
                case SCALE_ON_RANGE_AXIS:
                    zero = rangeAxis.valueToJava2D(0.0, dataArea, rangeAxisLocation);
                    transRange = zero - rangeAxis.valueToJava2D(z, dataArea, rangeAxisLocation);
                    transDomain = transRange;
                    break;
                default:
                    double zero1 = domainAxis.valueToJava2D(0.0, dataArea, domainAxisLocation);
                    double zero2 = rangeAxis.valueToJava2D(0.0, dataArea, rangeAxisLocation);
                    transDomain = domainAxis.valueToJava2D(z, dataArea, domainAxisLocation) - zero1;
                    transRange = zero2 - rangeAxis.valueToJava2D(z, dataArea, rangeAxisLocation);
                }
                transDomain = Math.abs(transDomain);
                transRange = Math.abs(transRange);

                // MODSCA 2008-11-27 enlarge ellipse by diag% of the total diagonal
                double diag = Math.sqrt(dataArea.getHeight() * dataArea.getHeight()
                        + dataArea.getWidth() * dataArea.getWidth());
                transDomain += diag / 100;
                transRange += diag / 100;

                Ellipse2D circle = null;

                // ADD xqliu 2009-07-06 bug 8035
                transDomain *= zSize;
                transRange *= zSize;
                // ~

                if (orientation == PlotOrientation.VERTICAL) {
                    circle = new Ellipse2D.Double(transX - transDomain / 2.0, transY - transRange / 2.0,
                            transDomain, transRange);
                } else if (orientation == PlotOrientation.HORIZONTAL) {
                    circle = new Ellipse2D.Double(transY - transRange / 2.0, transX - transDomain / 2.0,
                            transRange, transDomain);
                }
                g2.setPaint(getItemPaint(series, item));
                g2.fill(circle);
                g2.setStroke(getItemOutlineStroke(series, item));
                g2.setPaint(getItemOutlinePaint(series, item));
                g2.draw(circle);

                if (isItemLabelVisible(series, item)) {
                    if (orientation == PlotOrientation.VERTICAL) {
                        drawItemLabel(g2, orientation, dataset, series, item, transX, transY, false);
                    } else if (orientation == PlotOrientation.HORIZONTAL) {
                        drawItemLabel(g2, orientation, dataset, series, item, transY, transX, false);
                    }
                }

                // add an entity if this info is being collected
                EntityCollection entities = null;
                if (info != null) {
                    entities = info.getOwner().getEntityCollection();
                    if (entities != null && circle.intersects(dataArea)) {
                        addEntity(entities, circle, dataset, series, item, circle.getCenterX(),
                                circle.getCenterY());
                    }
                }

                int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
                int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
                updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY,
                        orientation);
            }

        }

        /**
         * DOC xqliu : calculate the size of bubble. for bug 8035 2009-07-06.
         * 
         * @param z multiple of bubble's default size
         * @return
         */
        private double getBubbleSize(double z) {
            if (z > 0 && z <= 10) {
                return 2;
            } else if (z > 10 && z <= 100) {
                return 3;
            } else if (z > 100) {
                return 4;
            }
            return 1;
        }

    };
    if (tooltips) {
        renderer.setBaseToolTipGenerator(new StandardXYZToolTipGenerator());
    }
    if (urls) {
        renderer.setURLGenerator(new StandardXYZURLGenerator());
    }
    plot.setRenderer(renderer);
    plot.setOrientation(orientation);

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

    return chart;

}

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

/**
 * Handles a 'mouse pressed' event.//from   w  w  w . ja va 2 s . c  o  m
 * <P>
 * This event is the popup trigger on Unix/Linux. For Windows, the popup trigger is the 'mouse
 * released' event.
 * 
 * @param e
 *            The mouse event.
 */

@Override
public void mousePressed(MouseEvent e) {
    if (this.chart == null) {
        return;
    }
    Plot plot = this.chart.getPlot();
    int mods = e.getModifiers();
    if ((mods & this.panMask) == this.panMask) {
        // can we pan this plot?
        if (plot instanceof Pannable) {
            Rectangle2D screenDataArea = getScreenDataArea(e.getX(), e.getY());
            if (screenDataArea != null && screenDataArea.contains(e.getPoint())) {
                this.panW = screenDataArea.getWidth();
                this.panH = screenDataArea.getHeight();
                this.panLast = e.getPoint();
                setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
            }
        }
    } else if (this.selectionRectangle == null) {
        Rectangle2D screenDataArea = getScreenDataArea(e.getX(), e.getY());
        if (screenDataArea != null) {
            this.zoomPoint = getPointInRectangle(e.getX(), e.getY(), screenDataArea);
        } else {
            this.zoomPoint = null;
        }
        if (e.isPopupTrigger()) {
            if (this.popup != null) {
                displayPopupMenu(e.getX(), e.getY());
            }
        }
    }
}

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

public void selectRectangle(Rectangle2D selection, MouseEvent selectionEvent) {
    Rectangle2D scaledDataArea = getScreenDataArea((int) selection.getCenterX(), (int) selection.getCenterY());
    if (selection.getHeight() > 0 && selection.getWidth() > 0) {

        double hLower = (selection.getMinX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth();
        double hUpper = (selection.getMaxX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth();
        double vLower = (scaledDataArea.getMaxY() - selection.getMaxY()) / scaledDataArea.getHeight();
        double vUpper = (scaledDataArea.getMaxY() - selection.getMinY()) / scaledDataArea.getHeight();

        Plot p = this.chart.getPlot();
        if (p instanceof XYPlot) {
            XYPlot plot = (XYPlot) p;//from  w w  w.j a  v  a2s  . c  o  m
            Selection selectionObject = new Selection();
            for (int i = 0; i < plot.getDomainAxisCount(); i++) {
                ValueAxis domain = plot.getDomainAxis(i);
                double lowerDomain = domain.getLowerBound();
                double upperDomain = domain.getUpperBound();
                Range axisRange = new Range(lowerDomain + (upperDomain - lowerDomain) * hLower,
                        lowerDomain + (upperDomain - lowerDomain) * hUpper);
                for (String axisName : axisNameResolver.resolveXAxis(i)) {
                    selectionObject.addDelimiter(axisName, axisRange);
                }
            }
            for (int i = 0; i < plot.getRangeAxisCount(); i++) {
                ValueAxis range = plot.getRangeAxis(i);
                double lowerRange = range.getLowerBound();
                double upperRange = range.getUpperBound();
                Range axisRange = new Range(lowerRange + (upperRange - lowerRange) * vLower,
                        lowerRange + (upperRange - lowerRange) * vUpper);
                for (String axisName : axisNameResolver.resolveYAxis(i)) {
                    selectionObject.addDelimiter(axisName, axisRange);
                }
            }
            informSelectionListener(selectionObject, selectionEvent);
        }
    }

}

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

/**
 * Returns the data area for the chart (the area inside the axes) with the current scaling
 * applied (that is, the area as it appears on screen).
 * //from  www  .  j  a va  2s  . c o m
 * @return The scaled data area.
 */

@Override
public Rectangle2D getScreenDataArea() {
    Rectangle2D dataArea = this.info.getPlotInfo().getDataArea();
    Insets insets = getInsets();
    double x = dataArea.getX() * this.scaleX + insets.left;
    double y = dataArea.getY() * this.scaleY + insets.top;
    double w = dataArea.getWidth() * this.scaleX;
    double h = dataArea.getHeight() * this.scaleY;
    return new Rectangle2D.Double(x, y, w, h);
}