Example usage for org.jfree.chart.axis ValueAxis java2DToValue

List of usage examples for org.jfree.chart.axis ValueAxis java2DToValue

Introduction

In this page you can find the example usage for org.jfree.chart.axis ValueAxis java2DToValue.

Prototype

public abstract double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge);

Source Link

Document

Converts a coordinate in Java2D space to the corresponding data value, assuming that the axis runs along one edge of the specified dataArea.

Usage

From source file:apidemo.PanScrollZoomDemo.java

/**
 * Decreases the range on the horizontal axis, centered about a Java2D x coordinate.
 * <P>//  www  .ja  v  a2  s. c om
 * The range on the x axis is multiplied by zoomFactor
 * 
 * @param x  the x coordinate in Java2D space.
 * @param zoomFactor  the zoomFactor < 1 == zoom in; else out.
 */
private void zoomHorizontal(final double x, final double zoomFactor) {

    final JFreeChart chart = this.chartPanel.getChart();
    final ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo();
    if (chart.getPlot() instanceof XYPlot) {
        final XYPlot hvp = (XYPlot) chart.getPlot();
        final ValueAxis axis = hvp.getDomainAxis();
        if (axis != null) {
            final double anchorValue = axis.java2DToValue((float) x, info.getPlotInfo().getDataArea(),
                    hvp.getDomainAxisEdge());
            if (zoomFactor < 1.0) {
                axis.resizeRange(zoomFactor, anchorValue);
            } else if (zoomFactor > 1.0) {
                final Range range = hvp.getDataRange(axis);
                adjustRange(axis, range, zoomFactor, anchorValue);
            }
        }
    }
}

From source file:apidemo.PanScrollZoomDemo.java

/**
 * Decreases the range on the vertical axis, centered about a Java2D y coordinate.
 * <P>/*www.j  a v  a 2s.c  o  m*/
 * The range on the y axis is multiplied by zoomFactor
 * 
 * @param y  the y coordinate in Java2D space.
 * @param zoomFactor  the zoomFactor < 1 == zoom in; else out.
 */
private void zoomVertical(final double y, final double zoomFactor) {

    final JFreeChart chart = this.chartPanel.getChart();
    final ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo();

    // 1. (left) Y-Axis

    if (chart.getPlot() instanceof XYPlot) {
        final XYPlot vvp = (XYPlot) chart.getPlot();
        final ValueAxis primYAxis = vvp.getRangeAxis();
        if (primYAxis != null) {
            final double anchorValue = primYAxis.java2DToValue((float) y, info.getPlotInfo().getDataArea(),
                    vvp.getRangeAxisEdge());
            if (zoomFactor < 1.0) {
                // zoom in
                primYAxis.resizeRange(zoomFactor, anchorValue);

            } else if (zoomFactor > 1.0) {
                // zoom out
                final Range range = new Range(this.primYMinMax[0], this.primYMinMax[1]);
                adjustRange(primYAxis, range, zoomFactor, anchorValue);
            }
        }

        // 2. (right) Y-Axis

        if (chart.getPlot() instanceof XYPlot) {
            final XYPlot xyp = (XYPlot) chart.getPlot();
            final ValueAxis secYAxis = xyp.getRangeAxis(1);
            if (secYAxis != null) {
                final double anchorValue = secYAxis.java2DToValue((float) y, info.getPlotInfo().getDataArea(),
                        xyp.getRangeAxisEdge(1));
                if (zoomFactor < 1.0) {
                    // zoom in
                    secYAxis.resizeRange(zoomFactor, anchorValue);

                } else if (zoomFactor > 1.0) {
                    // zoom out
                    final Range range = new Range(this.secondYMinMax[0], this.secondYMinMax[1]);
                    adjustRange(secYAxis, range, zoomFactor, anchorValue);
                }
            }
        }
    }
}

From source file:velocitekProStartAnalyzer.MainWindow.java

private void createChartPanel() {
    XYSeriesCollection dataset = JDBCPointDao.dataSet;
    JFreeChart chart = createChart(dataset);
    ChartPanel chartPanel = new ChartPanel(chart, true, false, false, true, false);
    chartPanel.setMinimumDrawWidth(0);/*from  www.ja  va 2s. c om*/
    chartPanel.setMinimumDrawHeight(0);
    chartPanel.setMaximumDrawWidth(1920);
    chartPanel.setMaximumDrawHeight(1200);
    chartPanel.getPopupMenu().addSeparator();
    chartPanel.getPopupMenu().add(btnAvgSpeedChart);
    chartPanel.getPopupMenu().add(btnMedianSpeedChart);
    chartPanel.getPopupMenu().add(btnResetSpeedChart);
    chartPanel.getPopupMenu().addSeparator();
    btnMenuSaveSubmenuForChart = new JMenu("Save");
    chartPanel.getPopupMenu().add(btnMenuSaveSubmenuForChart);

    if (JDBCPointDao.points.isEmpty()) {
        btnSaveAsVCC.setEnabled(false);
    }
    saveChartAsPng(chartPanel);

    btnMenuSaveSubmenuForChart.add(btnSaveChartAsPngForChart);
    btnMenuSaveSubmenuForChart.add(btnSaveTableAsPngForChart);
    btnMenuSaveSubmenuForChart.add(btnSaveMapAsPngForChart);
    btnMenuSaveSubmenuForChart.addSeparator();
    btnMenuSaveSubmenuForChart.add(btnSaveAsVCC);
    chartPanel.addChartMouseListener(new ChartMouseListener() {

        @Override
        public void chartMouseClicked(ChartMouseEvent event) {
            Rectangle2D dataArea = chartPanel.getScreenDataArea();
            JFreeChart chart = event.getChart();
            XYPlot plot = (XYPlot) chart.getPlot();
            ValueAxis xAxis = plot.getDomainAxis();
            double x = xAxis.java2DToValue(event.getTrigger().getX(), dataArea, RectangleEdge.BOTTOM);
            // make the crosshairs disappear if the mouse is out of range
            if (!xAxis.getRange().contains(x)) {
                x = Double.NaN;
            }

            x = Math.round(x);

            if (SwingUtilities.isLeftMouseButton(event.getTrigger()) && event.getTrigger().isShiftDown()) {
                for (PointDto cord : JDBCPointDao.points) {
                    {
                        if (cord.getPointID() == x) {
                            if (pointTable.getSelectionModel() == null) {
                                for (int i = 0; i < pointTable.getModel().getRowCount(); i++) {
                                    if (pointTable.getModel().getValueAt(i, 0).equals(cord.getPointID())) {
                                        pointTable.setRowSelectionInterval(i, i);
                                    }
                                }
                            } else {
                                for (int i = 0; i < pointTable.getModel().getRowCount(); i++) {
                                    if (pointTable.getModel().getValueAt(i, 0).equals(cord.getPointID())) {
                                        pointTable.addRowSelectionInterval(pointTable.getSelectedRow(), i);
                                    }
                                }
                            }
                            pointTable.scrollRectToVisible(
                                    pointTable.getCellRect(pointTable.getSelectedRow(), 0, true));
                        }
                    }
                }
            } else {
                for (PointDto cord : JDBCPointDao.points) {
                    {
                        if (cord.getPointID() == x) {
                            if (pointTable.getSelectionModel() != null) {
                                pointTable.getSelectionModel().clearSelection();
                            }
                            for (int i = 0; i < pointTable.getModel().getRowCount(); i++) {
                                if (pointTable.getModel().getValueAt(i, 0).equals(cord.getPointID())) {
                                    pointTable.setRowSelectionInterval(i, i);
                                }
                            }
                            pointTable.scrollRectToVisible(
                                    pointTable.getCellRect(pointTable.getSelectedRow(), 0, true));
                            //MainWindow.pointTable.revalidate();                      
                        }
                    }

                }
            }
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent event) {

            Rectangle2D dataArea = chartPanel.getScreenDataArea();
            JFreeChart chart = event.getChart();
            XYPlot plot = (XYPlot) chart.getPlot();
            ValueAxis xAxis = plot.getDomainAxis();
            double x = xAxis.java2DToValue(event.getTrigger().getX(), dataArea, RectangleEdge.BOTTOM);
            // make the crosshairs disappear if the mouse is out of range
            if (!xAxis.getRange().contains(x)) {
                x = Double.NaN;
            }
            double y = DatasetUtilities.findYValue(plot.getDataset(), 0, x);
            xCrosshair.setValue(x);
            yCrosshair.setValue(y);
            x = Math.round(x);
            for (PointDto cord : JDBCPointDao.points) {

                if (cord.getPointID() == x) {
                    mapPanel.map().removeMapMarker(mapPanel.getMapPoint());
                    mapPanel.setMapPoint(
                            new MapMarkerDot(null, null, cord.getPointLatidude(), cord.getPointLongtidude()));
                    mapPanel.setMapPoint(mapPanel.getMapPoint());
                    mapPanel.getMapPoint().setColor(colorMapMarkerCircle);
                    mapPanel.getMapPoint().setBackColor(colorMapMarkerHover);
                    mapPanel.map().addMapMarker(mapPanel.getMapPoint());
                }

            }
        }

    });
    XYPlot xyPlot = (XYPlot) chart.getPlot();
    ValueAxis rangeAxis = xyPlot.getRangeAxis();
    NavigableMap<Double, PointDto> pointDtoSortedSpeedMap = new TreeMap<Double, PointDto>();

    if (!JDBCPointDao.points.isEmpty()) {
        for (PointDto pointDto : JDBCPointDao.points) {
            pointDtoSortedSpeedMap.put(pointDto.getPointSpeed(), pointDto);
        }
        rangeAxis.setRange(pointDtoSortedSpeedMap.firstEntry().getKey() - 0.1,
                pointDtoSortedSpeedMap.lastEntry().getKey() + 0.1);
    }

    CrosshairOverlay crosshairOverlay = new CrosshairOverlay();
    xCrosshair = new Crosshair(Double.NaN, Color.GRAY, new BasicStroke(0f));
    xCrosshair.setLabelVisible(true);
    yCrosshair = new Crosshair(Double.NaN, Color.GRAY, new BasicStroke(0f));
    yCrosshair.setLabelVisible(true);
    crosshairOverlay.addDomainCrosshair(xCrosshair);
    crosshairOverlay.addRangeCrosshair(yCrosshair);
    chartPanel.addOverlay(crosshairOverlay);
    graphPanel.removeAll();
    graphPanel.add(chartPanel, BorderLayout.CENTER);
    graphPanel.revalidate();
    graphPanel.repaint();
    graphMapSplitPanel.revalidate();
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private boolean updateInvestPoint(Point2D _investPoint) {
    if (_investPoint == null) {
        return false;
    }/*from w  w w . j a va  2  s  . c  o m*/

    final ChartPanel chartPanel = this.investmentFlowChartJDialog.getChartPanel();
    final JFreeChart chart = chartPanel.getChart();
    final XYPlot plot = (XYPlot) chart.getPlot();
    final TimeSeriesCollection timeSeriesCollection = (TimeSeriesCollection) plot.getDataset();
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    // I also not sure why. This is what are being done in Mouse Listener Demo 4.
    //
    // Don't use it. It will cause us to lose precision.
    //final Point2D p2 = chartPanel.translateScreenToJava2D((Point)_investPoint);

    /* Try to get correct main chart area. */
    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();

    /* Believe it? When there is another thread keep updateing time series data,
     * and keep calling setDirty, _plotArea can be 0 size sometimes. Ignore it.
     * Just assume we had processed it.
     */
    if (_plotArea.getWidth() == 0.0 && _plotArea.getHeight() == 0.0) {
        /* Cheat the caller. */
        return true;
    }

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    final double coordinateX = domainAxis.java2DToValue(_investPoint.getX(), _plotArea, domainAxisEdge);

    int low = 0;
    int high = timeSeries.getItemCount() - 1;
    Date date = new Date((long) coordinateX);
    final long time = date.getTime();
    long bestDistance = Long.MAX_VALUE;
    int bestMid = 0;

    while (low <= high) {
        int mid = (low + high) >>> 1;

        final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(mid);
        final Day day = (Day) timeSeriesDataItem.getPeriod();
        final long search = day.getFirstMillisecond();
        final long cmp = search - time;

        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            bestDistance = 0;
            bestMid = mid;
            break;
        }

        final long abs_cmp = Math.abs(cmp);
        if (abs_cmp < bestDistance) {
            bestDistance = abs_cmp;
            bestMid = mid;
        }
    }

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(bestMid);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final double xJava2D = domainAxis.valueToJava2D(xValue, _plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, _plotArea, rangeAxisEdge);

    final int tmpIndex = bestMid;
    // Do not perform translation as this will cause precision losing.
    // We might experience unstable point. For example,
    //
    // this.investPoint is 700.9, there are 2 data points which are 700 and
    // 701.
    // During first updateInvestPoint(this.investPoint) call, data point 701
    // will be chosen, and this.investPoint has been truncated to 700.
    // During second updateInvestPoint(this.investPoint) call, data point 700
    // will be chosen. We may observe an unstable point swings between 700
    // and 701.
    //
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    //final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    final Point2D tmpPoint = new Point2D.Double(xJava2D, yJava2D);
    this.drawArea.setRect(_plotArea);

    if (this.drawArea.contains(tmpPoint)) {
        this.investPointIndex = tmpIndex;
        this.investPoint = tmpPoint;
        return true;
    }
    return false;
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private boolean updateROIPoint(Point2D _ROIPoint) {
    if (_ROIPoint == null) {
        return false;
    }//  w w w .j  a v  a 2  s.com

    final ChartPanel chartPanel = this.investmentFlowChartJDialog.getChartPanel();
    final JFreeChart chart = chartPanel.getChart();
    final XYPlot plot = (XYPlot) chart.getPlot();
    // Dataset 0 are the invest information. 1 is the ROI information.
    final TimeSeriesCollection timeSeriesCollection = (TimeSeriesCollection) plot.getDataset(1);
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    // I also not sure why. This is what are being done in Mouse Listener Demo 4.
    //
    // Don't use it. It will cause us to lose precision.
    //final Point2D p2 = chartPanel.translateScreenToJava2D((Point)_ROIPoint);

    /* Try to get correct main chart area. */
    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();

    /* Believe it? When there is another thread keep updateing time series data,
     * and keep calling setDirty, _plotArea can be 0 size sometimes. Ignore it.
     * Just assume we had processed it.
     */
    if (_plotArea.getWidth() == 0.0 && _plotArea.getHeight() == 0.0) {
        /* Cheat the caller. */
        return true;
    }

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    final double coordinateX = domainAxis.java2DToValue(_ROIPoint.getX(), _plotArea, domainAxisEdge);

    int low = 0;
    int high = timeSeries.getItemCount() - 1;
    Date date = new Date((long) coordinateX);
    final long time = date.getTime();
    long bestDistance = Long.MAX_VALUE;
    int bestMid = 0;

    while (low <= high) {
        int mid = (low + high) >>> 1;

        final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(mid);
        final Day day = (Day) timeSeriesDataItem.getPeriod();
        final long search = day.getFirstMillisecond();
        final long cmp = search - time;

        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            bestDistance = 0;
            bestMid = mid;
            break;
        }

        final long abs_cmp = Math.abs(cmp);
        if (abs_cmp < bestDistance) {
            bestDistance = abs_cmp;
            bestMid = mid;
        }
    }

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(bestMid);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final double xJava2D = domainAxis.valueToJava2D(xValue, _plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, _plotArea, rangeAxisEdge);

    final int tmpIndex = bestMid;
    // Do not perform translation as this will cause precision losing.
    // We might experience unstable point. For example,
    //
    // this.ROIPoint is 700.9, there are 2 data points which are 700 and
    // 701.
    // During first updateROIPoint(this.ROIPoint) call, data point 701
    // will be chosen, and this.ROIPoint has been truncated to 700.
    // During second updateROIPoint(this.ROIPoint) call, data point 700
    // will be chosen. We may observe an unstable point swings between 700
    // and 701.
    //
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    //final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    final Point2D tmpPoint = new Point2D.Double(xJava2D, yJava2D);
    this.drawArea.setRect(_plotArea);

    if (this.drawArea.contains(tmpPoint)) {
        this.ROIPointIndex = tmpIndex;
        this.ROIPoint = tmpPoint;
        return true;
    }
    return false;
}

From source file:org.yccheok.jstock.gui.charting.ChartLayerUI.java

private boolean _updateMainTraceInfoForCandlestick(Point2D point) {
    if (point == null) {
        return false;
    }/* www .  j  a  v  a 2  s.co  m*/

    final ChartPanel chartPanel = this.chartJDialog.getChartPanel();
    // Top most plot.
    final XYPlot plot = this.chartJDialog.getPlot();

    final org.jfree.data.xy.DefaultHighLowDataset defaultHighLowDataset = (org.jfree.data.xy.DefaultHighLowDataset) plot
            .getDataset();

    // I also not sure why. This is what are being done in Mouse Listener Demo 4.
    //
    // Don't use it. It will cause us to lose precision.
    //final Point2D p2 = chartPanel.translateScreenToJava2D((Point)point);

    /* Try to get correct main chart area. */
    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getSubplotInfo(0)
            .getDataArea();

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    // Don't use it. It will cause us to lose precision.
    //final double coordinateX = domainAxis.java2DToValue(p2.getX(), _plotArea,
    //        domainAxisEdge);
    final double coordinateX = domainAxis.java2DToValue(point.getX(), _plotArea, domainAxisEdge);
    //double coordinateY = rangeAxis.java2DToValue(mousePoint2.getY(), plotArea,
    //        rangeAxisEdge);

    int low = 0;
    int high = defaultHighLowDataset.getItemCount(0) - 1;
    Date date = new Date((long) coordinateX);
    final long time = date.getTime();
    long bestDistance = Long.MAX_VALUE;
    int bestMid = 0;

    while (low <= high) {
        int mid = (low + high) >>> 1;

        final Date d = defaultHighLowDataset.getXDate(0, mid);
        final long search = d.getTime();
        final long cmp = search - time;

        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            bestDistance = 0;
            bestMid = mid;
            break;
        }

        final long abs_cmp = Math.abs(cmp);
        if (abs_cmp < bestDistance) {
            bestDistance = abs_cmp;
            bestMid = mid;
        }
    }

    final double xValue = defaultHighLowDataset.getXDate(0, bestMid).getTime();
    final double yValue = defaultHighLowDataset.getCloseValue(0, bestMid);
    final double xJava2D = domainAxis.valueToJava2D(xValue, _plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, _plotArea, rangeAxisEdge);

    final int tmpIndex = bestMid;
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    this.mainDrawArea.setRect(_plotArea);

    if (this.mainDrawArea.contains(tmpPoint)) {
        // 0 indicates main plot.
        this.mainTraceInfo = TraceInfo.newInstance(tmpPoint, 0, 0, tmpIndex);
        return true;
    }
    return false;
}

From source file:org.yccheok.jstock.gui.charting.ChartLayerUI.java

private boolean updateMainTraceInfo(Point2D point) {
    if (point == null) {
        return false;
    }/*from   w w  w .  j a  v a2s  .  c  om*/

    final ChartPanel chartPanel = this.chartJDialog.getChartPanel();
    // Top most plot.
    final XYPlot plot = this.chartJDialog.getPlot();

    if (plot.getDataset() instanceof org.jfree.data.xy.DefaultHighLowDataset) {
        return this._updateMainTraceInfoForCandlestick(point);
    }

    final TimeSeriesCollection timeSeriesCollection = (TimeSeriesCollection) plot.getDataset();
    // 0 are the main chart. 1, 2, 3... are TA.
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    // I also not sure why. This is what are being done in Mouse Listener Demo 4.
    //
    // Don't use it. It will cause us to lose precision.
    //final Point2D p2 = chartPanel.translateScreenToJava2D((Point)point);

    /* Try to get correct main chart area. */
    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getSubplotInfo(0)
            .getDataArea();

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    // Don't use it. It will cause us to lose precision.
    //final double coordinateX = domainAxis.java2DToValue(p2.getX(), _plotArea,
    //        domainAxisEdge);
    final double coordinateX = domainAxis.java2DToValue(point.getX(), _plotArea, domainAxisEdge);
    //double coordinateY = rangeAxis.java2DToValue(mousePoint2.getY(), plotArea,
    //        rangeAxisEdge);

    int low = 0;
    int high = timeSeries.getItemCount() - 1;
    Date date = new Date((long) coordinateX);
    final long time = date.getTime();
    long bestDistance = Long.MAX_VALUE;
    int bestMid = 0;

    while (low <= high) {
        int mid = (low + high) >>> 1;

        final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(mid);
        final Day day = (Day) timeSeriesDataItem.getPeriod();
        final long search = day.getFirstMillisecond();
        final long cmp = search - time;

        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            bestDistance = 0;
            bestMid = mid;
            break;
        }

        final long abs_cmp = Math.abs(cmp);
        if (abs_cmp < bestDistance) {
            bestDistance = abs_cmp;
            bestMid = mid;
        }
    }

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(bestMid);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final double xJava2D = domainAxis.valueToJava2D(xValue, _plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, _plotArea, rangeAxisEdge);

    final int tmpIndex = bestMid;
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    this.mainDrawArea.setRect(_plotArea);

    if (this.mainDrawArea.contains(tmpPoint)) {
        // 0 indicates main plot.
        this.mainTraceInfo = TraceInfo.newInstance(tmpPoint, 0, 0, tmpIndex);
        return true;
    }
    return false;
}

From source file:org.tsho.dmc2.core.chart.Bifurcation2DRenderer.java

public void render(final Graphics2D g2, final Rectangle2D dataArea, final PlotRenderingInfo info) {

    int numVar = model.getNVar();

    if (model instanceof ODE) {

        boolean pointBeyondPoincareSection;
        ValueAxis domainAxis = plot.getDomainAxis();
        ValueAxis rangeAxis = plot.getRangeAxis();

        int dim = initialValue.length;

        final int colorArrayLen = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length;
        final Paint[] colorArray = new Color[colorArrayLen];
        for (int i = 0; i < colorArrayLen; i++) {
            colorArray[i] = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i];
        }/*from  w w w . j a  v a  2  s  .  c  om*/

        double[] fPars = new double[fixedParameters.length];
        System.arraycopy(fixedParameters, 0, fPars, 0, fixedParameters.length);
        double[] initVars = new double[initialValue.length];
        System.arraycopy(initialValue, 0, initVars, 0, initialValue.length);

        double[] result = new double[dim];
        double[][] periodArray = new double[period][dim];

        for (double i = dataArea.getMinX(); i <= dataArea.getMaxX(); i += 1) {

            fPars[firstParameterIdx] = domainAxis.java2DToValue(i, dataArea, RectangleEdge.BOTTOM);

            for (double j = dataArea.getMinY(); j < dataArea.getMaxY(); j += 1) {

                fPars[secondParameterIdx] = rangeAxis.java2DToValue(j, dataArea, RectangleEdge.LEFT);

                stepper.setParameters(fPars);
                stepper.setInitialValue(initVars);
                stepper.initialize();
                stepper.step();
                stepper.getCurrentValue(result);

                int h = 0;
                int transX, transY;

                double[] currentPoint = new double[numVar];
                double[] previousPoint = new double[numVar];
                stepper.getCurrentValue(currentPoint);
                stepper.getCurrentValue(previousPoint);
                pointBeyondPoincareSection = positionWrtPoincareSection(currentPoint);

                Paint color = Color.white;
                double[] cycleStartPoint = new double[numVar];
                int actualPeriod = period + 1;

                for (int jj = 0; jj < time / step; jj++) {
                    stepper.step();
                    stepper.getCurrentValue(currentPoint);

                    if (positionWrtPoincareSection(currentPoint) == pointBeyondPoincareSection) {
                        stepper.getCurrentValue(previousPoint);
                        continue;
                    }

                    pointBeyondPoincareSection = !pointBeyondPoincareSection;
                    double[] pointOnSection = pointOnPoincareSection(previousPoint, currentPoint);
                    stepper.setInitialValue(pointOnSection);
                    stepper.initialize();
                    stepper.getCurrentValue(currentPoint);
                    stepper.getCurrentValue(previousPoint);

                    h++;

                    if (h == transients) {
                        for (int kk = 0; kk < numVar; kk++)
                            cycleStartPoint[kk] = currentPoint[kk];
                    }
                    if (h > transients) {
                        if (distance(currentPoint, cycleStartPoint) < epsilon) {
                            actualPeriod = h - transients;
                            break;
                        }
                        if (h >= transients + period)
                            break;
                    }
                }

                stepper.getCurrentValue(result);

                for (h = 0; h < dim; h++) {
                    if (Math.abs(result[h]) > infinity || Double.isNaN(result[h])) {
                        color = Color.black; // black == infinity
                    }
                }

                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }

                if (actualPeriod <= period) { // found period
                    color = colorArray[actualPeriod - 1];
                }

                g2.setPaint(color);
                g2.drawRect((int) i, (int) j, 1, 1);

                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }
            }

        }
        state = STATE_FINISHED;

    } else {
        ValueAxis domainAxis = plot.getDomainAxis();
        ValueAxis rangeAxis = plot.getRangeAxis();

        int dim = initialValue.length;

        final int colorArrayLen = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length;
        final Paint[] colorArray = new Color[colorArrayLen];
        for (int i = 0; i < colorArrayLen; i++) {
            colorArray[i] = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i];
        }

        double[] fPars = new double[fixedParameters.length];
        System.arraycopy(fixedParameters, 0, fPars, 0, fixedParameters.length);
        double[] initVars = new double[initialValue.length];
        System.arraycopy(initialValue, 0, initVars, 0, initialValue.length);

        double[] result = new double[dim];
        double[][] periodArray = new double[period + 1][dim];

        for (double i = dataArea.getMinX(); i <= dataArea.getMaxX(); i += 1) {

            fPars[firstParameterIdx] = domainAxis.java2DToValue(i, dataArea, RectangleEdge.BOTTOM);

            for (double j = dataArea.getMinY(); j < dataArea.getMaxY(); j += 1) {

                fPars[secondParameterIdx] = rangeAxis.java2DToValue(j, dataArea, RectangleEdge.LEFT);

                stepper.setParameters(fPars);
                stepper.setInitialValue(initVars);
                stepper.initialize();
                stepper.step();
                stepper.getCurrentValue(result);

                for (int h = 1; h < transients; h++) {
                    if (stopped) {
                        state = STATE_STOPPED;
                        return;
                    }
                    stepper.step();
                }

                stepper.getCurrentValue(result);

                Paint color = Color.white; // white == longer period
                for (int h = 0; h < dim; h++) {
                    if (Math.abs(result[h]) > infinity || Double.isNaN(result[h])) {
                        color = Color.black; // black == infinity
                        break;
                    }
                }

                if (color != Color.black) {
                    // get maxPeriod next values
                    for (int h = 0; h <= period; h++) {
                        if (stopped) {
                            state = STATE_STOPPED;
                            return;
                        }

                        stepper.step();
                        stepper.getCurrentValue(result);

                        for (int k = 0; k < dim; k++) {
                            periodArray[h][k] = result[k];
                        }
                    }

                    int h, k = -1;
                    for (h = 1; h <= period; h++) {
                        for (k = 0; k < dim; k++) {
                            if (Math.abs(periodArray[0][k] - periodArray[h][k]) >= epsilon) {
                                break;
                            }
                        }
                        if (k == dim) {
                            break;
                        }
                    }

                    if (h <= period) { // found period
                        color = colorArray[h - 1];
                    }
                }
                g2.setPaint(color);
                g2.drawRect((int) i, (int) j, 1, 1);

                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }
            }
        }
        state = STATE_FINISHED;
    }

}

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

/**
 * This method attempts to get a tooltip by converting the screen X,Y into Chart Area X,Y and then looking for a
 * data point in a data set that lies inside a hotspot around that value.
 * //from   ww  w.  ja  va2 s. co m
 * @param point The Java 2D point
 * @return A string for the data at the point or null if no data is found.
 */
protected String getTooltipAtPoint(Point point) {
    String result = null;

    Point2D translatedPoint = this.translateScreenToJava2D(point);
    Plot plot = this.getChart().getPlot();
    PlotRenderingInfo info = this.getChartRenderingInfo().getPlotInfo();
    if (plot instanceof CombinedDomainXYPlot) {
        int index = info.getSubplotIndex(translatedPoint);
        if (index < 0) {
            index = 0;
        }
        plot = (Plot) ((CombinedDomainXYPlot) plot).getSubplots().get(index);
        info = this.getChartRenderingInfo().getPlotInfo().getSubplotInfo(index);
    }
    if (plot != null && plot instanceof XYPlot) {
        XYPlot xyPlot = (XYPlot) plot;
        ValueAxis domainAxis = xyPlot.getDomainAxis();
        ValueAxis rangeAxis = xyPlot.getRangeAxis();
        // had to switch to SWT's rectangle here.
        Rectangle screenArea = this.scale(info.getDataArea());

        double hotspotSizeX = hotspontsize * this.getScaleX();
        double hotspotSizeY = hotspontsize * this.getScaleY();
        double x0 = point.getX();
        double y0 = point.getY();
        double x1 = x0 - hotspotSizeX;
        double y1 = y0 + hotspotSizeY;
        double x2 = x0 + hotspotSizeX;
        double y2 = y0 - hotspotSizeY;
        RectangleEdge xEdge = RectangleEdge.BOTTOM;
        RectangleEdge yEdge = RectangleEdge.LEFT;
        // Switch everything for horizontal charts
        if (xyPlot.getOrientation() == PlotOrientation.HORIZONTAL) {
            hotspotSizeX = hotspontsize * this.getScaleY();
            hotspotSizeY = hotspontsize * this.getScaleX();
            x0 = point.getY();
            y0 = point.getX();
            x1 = x0 + hotspotSizeX;
            y1 = y0 - hotspotSizeY;
            x2 = x0 - hotspotSizeX;
            y2 = y0 + hotspotSizeY;
            xEdge = RectangleEdge.LEFT;
            yEdge = RectangleEdge.BOTTOM;
        }

        // OK, here we have to get ourselves back into AWT land...
        Rectangle2D r2d = new Rectangle2D.Double();
        r2d.setRect(screenArea.x, screenArea.y, screenArea.width, screenArea.height);

        double ty0 = rangeAxis.java2DToValue(y0, r2d, yEdge);
        double tx1 = domainAxis.java2DToValue(x1, r2d, xEdge);
        double ty1 = rangeAxis.java2DToValue(y1, r2d, yEdge);
        double tx2 = domainAxis.java2DToValue(x2, r2d, xEdge);
        double ty2 = rangeAxis.java2DToValue(y2, r2d, yEdge);

        int datasetCount = xyPlot.getDatasetCount();
        for (int datasetIndex = 0; datasetIndex < datasetCount; datasetIndex++) {
            XYDataset dataset = xyPlot.getDataset(datasetIndex);
            int seriesCount = dataset.getSeriesCount();
            for (int series = 0; series < seriesCount; series++) {
                int itemCount = dataset.getItemCount(series);
                if (dataset instanceof OHLCDataset) {
                    // This could be optimized to use a binary search for x first
                    for (int item = 0; item < itemCount; item++) {
                        double xValue = dataset.getXValue(series, item);
                        double yValueHi = ((OHLCDataset) dataset).getHighValue(series, item);
                        double yValueLo = ((OHLCDataset) dataset).getLowValue(series, item);
                        // Check hi lo and swap if needed
                        if (yValueHi < yValueLo) {
                            double temp = yValueHi;
                            yValueHi = yValueLo;
                            yValueLo = temp;
                        }
                        // Check if the dataset 'X' value lies between the hotspot (tx1 < xValue < tx2)
                        if (tx1 < xValue && xValue < tx2) {
                            // Check if the cursor 'y' value lies between the high and low (low < ty0 < high)
                            if (yValueLo < ty0 && ty0 < yValueHi) {
                                return hiLoTips.generateToolTip(dataset, series, item);
                            }
                        }
                    }
                } else {
                    // This could be optimized to use a binary search for x first
                    for (int item = 0; item < itemCount; item++) {
                        double xValue = dataset.getXValue(series, item);
                        double yValue = dataset.getYValue(series, item);
                        // Check if the dataset 'X' value lies between the hotspot (tx1< xValue < tx2)
                        if (tx1 < xValue && xValue < tx2) {
                            // Check if the dataset 'Y' value lies between the hotspot (ty1 < yValue < ty2)
                            if (ty1 < yValue && yValue < ty2) {
                                return xyTips.generateToolTip(dataset, series, item);
                            }
                        }
                    }
                }
            }
        }
    }

    return result;
}

From source file:edu.ucla.stat.SOCR.chart.demo.SOCR_EM_MixtureModelChartDemo.java

public Point2D getPointInChart(MouseEvent e) {
    Insets insets = getInsets();//w  w  w.ja va  2 s.com
    //System.out.println("inset.top="+insets.top+" inset.left="+insets.left);
    //System.out.println("scaleX="+chartPaneltest.getScaleX()+" scaleY="+chartPaneltest.getScaleY());
    //System.out.println(e.getX());
    //   int mouseX = (int) ((e.getX() - insets.left) / chartPaneltest.getScaleX());
    //   int mouseY = (int) ((e.getY() - insets.top) / chartPaneltest.getScaleY());
    int mouseX = (int) (e.getX() - insets.left);
    int mouseY = (int) (e.getY() - insets.top);
    //   Point2D pt = new Point2D.Double();
    //pt.setLocation(mouseX, mouseY);
    //return pt;

    //   System.out.println("x = " + mouseX + ", y = " + mouseY);

    Point2D p = chartPaneltest.translateScreenToJava2D(new Point(mouseX, mouseY));
    XYPlot plot = (XYPlot) chart.getPlot();
    ChartRenderingInfo info = chartPaneltest.getChartRenderingInfo();
    Rectangle2D dataArea = info.getPlotInfo().getDataArea();

    ValueAxis domainAxis = plot.getDomainAxis();
    RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    ValueAxis rangeAxis = plot.getRangeAxis();
    RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();

    double chartX = domainAxis.java2DToValue(p.getX(), dataArea, domainAxisEdge);
    double chartY = rangeAxis.java2DToValue(p.getY(), dataArea, rangeAxisEdge);
    Point2D pt2 = new Point2D.Double();

    //double scale = (double)CHART_SIZE_X/(double)CHART_SIZE_Y;
    //System.out.println("scale="+scale);
    pt2.setLocation(chartX, chartY);
    //System.out.println("Chart: x = " + (chartX) + ", y = " + chartY);
    return pt2;

}