Example usage for java.awt Graphics2D drawLine

List of usage examples for java.awt Graphics2D drawLine

Introduction

In this page you can find the example usage for java.awt Graphics2D drawLine.

Prototype

public abstract void drawLine(int x1, int y1, int x2, int y2);

Source Link

Document

Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.

Usage

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

public boolean renderVsTime(Graphics2D g2, Rectangle2D dataArea) {

    final int imageWidth = (int) dataArea.getWidth();

    g2.setPaint(Color.red);// w w w .  j ava 2  s . c  o  m

    final int timeStep;
    if (Math.abs(upper - lower) >= imageWidth) {
        timeStep = ((int) upper - (int) lower) / imageWidth;
    } else {
        timeStep = 1;
    }

    CoreStatusEvent statusEv = new CoreStatusEvent(this);

    int prevX[] = new int[model.getNVar()];
    int prevY[] = new int[model.getNVar()];

    int ratio = (int) upper / 100;
    for (int i = (int) lower; i < (int) upper; i += timeStep) {
        double[] result;
        int transX, transY;

        result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, i);

        for (int j = 0; j < result.length; j++) {
            transX = (int) this.domainAxis.valueToJava2D(i, dataArea, RectangleEdge.BOTTOM);
            transY = (int) this.rangeAxis.valueToJava2D(result[j], dataArea, RectangleEdge.LEFT);
            //                        System.out.println("time: " + i);
            //                        System.out.println("ly[" + j + "] = " + result[j]);
            //                        System.out.println("x: " + transX + " y: " + transY);
            g2.setPaint(paintSequence[j]);
            //g2.fillRect(transX, transY, 1, 1);

            if (bigDots) {
                g2.fillRect(transX - 1, transY - 1, 3, 3);

            } else {
                g2.fillRect(transX, transY, 1, 1);
            }

            if (connectWithLines) {
                if (i > (int) lower) {
                    g2.drawLine(transX, transY, prevX[j], prevY[j]);
                }

                prevX[j] = transX;
                prevY[j] = transY;
            }
        }

        if (stopped == true) {
            return false;
        } else if (ratio > 0) {
            statusEv.setPercent(i / ratio);
            statusEv.setType(CoreStatusEvent.COUNT | CoreStatusEvent.PERCENT);
            notifyCoreStatusListeners(statusEv);
        }

    }

    return true;
}

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

public boolean renderVsParameter(Graphics2D g2, Rectangle2D dataArea) {

    final int imageWidth = (int) dataArea.getWidth();

    g2.setPaint(Color.red);//ww w.  j  a  va 2  s  .  c  o  m

    final double parStep;
    parStep = Math.abs(upper - lower) / imageWidth;

    CoreStatusEvent statusEv = new CoreStatusEvent(this);

    //int ratio = upper / 100;

    int prevX[] = new int[model.getNVar()];
    int prevY[] = new int[model.getNVar()];

    for (double i = lower; i < upper; i += parStep) {
        double[] result;
        int transX, transY;

        parameters.put(firstParLabel, i);

        try {
            result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, iterations);
        } catch (ModelException e) {
            String mess = "Exception while:\n" + dumpVariableDoubles(parameters)
                    + dumpVariableDoubles(initialPoint);
            throw new ModelException(mess, e);
        }

        for (int j = 0; j < result.length; j++) {

            transX = (int) this.domainAxis.valueToJava2D(i, dataArea, RectangleEdge.BOTTOM);

            transY = (int) this.rangeAxis.valueToJava2D(result[j], dataArea, RectangleEdge.LEFT);

            //                System.out.println("ly[" + j + "] = " + result[j]);
            //                System.out.println("x: " + transX + " y: " + transY);

            g2.setPaint(paintSequence[j]);
            //g2.fillRect(transX, transY, 1, 1);
            if (bigDots) {
                g2.fillRect(transX - 1, transY - 1, 3, 3);

            } else {
                g2.fillRect(transX, transY, 1, 1);
            }

            if (connectWithLines) {
                if (i != lower) {
                    g2.drawLine(transX, transY, prevX[j], prevY[j]);
                }

                prevX[j] = transX;
                prevY[j] = transY;
            }
        }

        if (stopped == true) {
            return false;
        }
        //else if (ratio > 0 && i % ratio == 0) {
        statusEv.setPercent(0);
        statusEv.setType(CoreStatusEvent.COUNT | CoreStatusEvent.PERCENT);
        notifyCoreStatusListeners(statusEv);
        //}

    }

    return true;
}

From source file:spinworld.gui.RadarPlot.java

private void drawTicks(Graphics2D g2, Rectangle2D radarArea, double axisAngle, int cat) {
    double[] ticks = { 0.5d, 1d };
    for (int i = 0; i < ticks.length; i++) {
        double tick = ticks[i];
        Point2D middlePoint = getWebPoint(radarArea, axisAngle, tick);
        double xt = middlePoint.getX();
        double yt = middlePoint.getY();
        double angrad = Math.toRadians(-axisAngle);
        g2.translate(xt, yt);//from  ww  w  .j  a  v a  2s  .  c o m
        g2.rotate(angrad);
        g2.drawLine(0, (int) -TICK_MARK_LENGTH / 2, 0, (int) TICK_MARK_LENGTH / 2);
        g2.rotate(-angrad);
        g2.translate(-xt, -yt);
        drawTickLabel(g2, radarArea, middlePoint, axisAngle, cat, tick);
    }
}

From source file:com.github.andreax79.meca.Main.java

public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern,
        int steps, double alpha, String pattern, Output output, ColorScheme colorScheme) throws IOException {
    Rule rule = new Rule(ruleNumber);
    Row row = new Row(size, rule, boundaries, updatePattern, pattern, alpha); // e.g. 00010011011111
    Stats stats = new Stats();

    FileOutputStream finalImage = null;
    Graphics2D g = null;
    BufferedImage img = null;/*from   w ww  . ja v  a2s. c om*/

    if (output != Output.noOutput) {
        String fileName = "rule" + ruleNumber;
        // pattern
        if (pattern != null)
            fileName += pattern;
        // alpha
        if (alpha > 0)
            fileName += String.format("_a%02d", (int) (alpha * 100));
        // updatePattern
        if (updatePattern != UpdatePattern.synchronous)
            fileName += "-" + updatePattern;
        fileName += ".jpeg";

        File file = new File(fileName);
        finalImage = new FileOutputStream(file);

        int width = (int) (cellSize * (size + 1) * (output == Output.all ? 1.25 : 1));
        int height = cellSize * (steps + 1);
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        g = img.createGraphics();
        g.setBackground(Color.white);
        g.clearRect(0, 0, width, height);
        g.setColor(Color.black);
    }

    int startMeansFromStep = 50;
    List<Double> densities = new LinkedList<Double>();
    double totalDensities = 0;

    double prevValue = 0;
    double prevDelta = 0;
    double prevOnes = 0;
    double prevOnesDelta = 0;

    for (int t = 0; t < steps; t++) {
        if (t >= startMeansFromStep) {
            double density = row.getDensity();
            densities.add(density);
            totalDensities += density;
        }
        // System.out.println(String.format("%4d", t) + " " + row.toString() + " ones=" + row.getOnes());
        if (output != Output.noOutput) {
            for (int j = 0; j < row.getSize(); j++) {

                switch (colorScheme) {
                case noColor:
                    if (row.getCell(j).getState()) {
                        g.setColor(Color.black);
                        g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    }
                    break;
                case omegaColor:
                    g.setColor(row.getCell(j).getOmegaColor());
                    g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    break;
                case activationColor:
                    if (row.getCell(j).getState()) {
                        g.setColor(row.getCell(j).getColor());
                        g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    }
                    break;
                }
            }

            if (output == Output.all) {
                double value = row.getValue();
                double delta = Math.abs(value - prevValue);
                double ones = row.getOnes();
                double onesDelta = Math.abs(ones - prevOnes);
                if (t > 0) {
                    g.setColor(Color.red);
                    g.drawLine((int) (prevValue * cellSize / 4.0) + cellSize * (size + 1),
                            (int) ((t - 1) * cellSize), (int) (value * cellSize / 4.0) + cellSize * (size + 1),
                            (int) (t * cellSize));
                    g.setColor(Color.blue);
                    g.drawLine((int) (prevOnes * cellSize / 4.0) + cellSize * (size + 1),
                            (int) ((t - 1) * cellSize), (int) (ones * cellSize / 4.0) + cellSize * (size + 1),
                            (int) (t * cellSize));
                    if (t > 1) {
                        g.setColor(Color.orange);
                        g.drawLine((int) (prevDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) ((t - 1) * cellSize),
                                (int) (delta * cellSize / 4.0) + cellSize * (size + 1), (int) (t * cellSize));
                        g.setColor(Color.cyan);
                        g.drawLine((int) (prevOnesDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) ((t - 1) * cellSize),
                                (int) (onesDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) (t * cellSize));
                    }
                }
                prevValue = value;
                prevDelta = delta;
                prevOnes = ones;
                prevOnesDelta = onesDelta;
            }
        }

        row = new Row(row);
    }

    double means = totalDensities / densities.size();
    double var = 0;
    for (double density : densities)
        var += Math.pow(density - means, 2);
    var = var / densities.size();
    System.out.println("Rule: " + ruleNumber + " Boundaties: " + boundaries + " UpdatePattern: " + updatePattern
            + " Alpha: " + String.format("%.3f", alpha) + " Means: " + String.format("%.6f", means)
            + " Variance: " + String.format("%.6f", var));
    stats.setMeans(means);
    stats.setVariance(var);

    if (output != Output.noOutput) {
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(finalImage);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
        param.setQuality(1.0f, true);
        encoder.encode(img, param);
        finalImage.flush();
        finalImage.close();
    }

    return stats;
}

From source file:org.broad.igv.variant.VariantTrack.java

/**
 * Renders the top line, bottom track line, and border between variants / genotypes
 *
 * @param g2D/*from   w  ww. j  a  v a  2s .  co  m*/
 * @param trackRectangle
 * @param visibleRectangle
 */
private void renderBoundaryLines(Graphics2D g2D, Rectangle trackRectangle, Rectangle visibleRectangle) {
    top = trackRectangle.y;
    final int left = trackRectangle.x;
    final int right = (int) trackRectangle.getMaxX();

    //Top line
    drawLineIfVisible(g2D, visibleRectangle, Color.black, top + 1, left, right);

    // Bottom border
    int bottomY = trackRectangle.y + trackRectangle.height;
    drawLineIfVisible(g2D, visibleRectangle, borderGray, bottomY, left, right);

    // Variant / Genotype border
    int variantGenotypeBorderY = trackRectangle.y + getVariantsHeight();
    drawVariantBandBorder(g2D, visibleRectangle, variantGenotypeBorderY, left, right);

    if (grouped) {
        g2D.setColor(Color.black);
        int y = trackRectangle.y + getVariantsHeight();
        for (Map.Entry<String, List<String>> entry : samplesByGroups.entrySet()) {
            y += entry.getValue().size() * getGenotypeBandHeight() + GROUP_BORDER_WIDTH;
            g2D.drawLine(trackRectangle.x, y, trackRectangle.x + trackRectangle.width, y);
        }
    }
}

From source file:ucar.unidata.idv.control.chart.MyScatterPlot.java

/**
 * Draws the fast scatter plot on a Java 2D graphics device (such as the
 * screen or a printer).// w  w  w . j  av a 2s .  c o m
 * a
 * @param g2  the graphics device.
 * @param dataArea the data area
 * @param index which data set
 * @param info  collects chart drawing information (<code>null</code>
 *              permitted).
 * @param crosshairState crosshairState
 *
 * @return did something
 */
public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info,
        CrosshairState crosshairState) {

    if (index >= series.size()) {
        return false;
    }
    XYDataset dataset = getDataset(index);
    g2.setStroke(new BasicStroke());
    //                   getRendererForDataset(dataset).getSeriesStroke(0));
    ScatterPlotChartWrapper.MyRenderer renderer = (ScatterPlotChartWrapper.MyRenderer) getRendererForDataset(
            dataset);
    g2.setPaint(renderer.getSeriesPaint(0));
    int shape = renderer.shape;

    PlotOrientation orientation = getOrientation();
    int seenCnt = 0;

    int xx = (int) dataArea.getMinX();
    int ww = (int) dataArea.getWidth();
    int yy = (int) dataArea.getMaxY();
    int hh = (int) dataArea.getHeight();
    ValueAxis rangeAxis = getRangeAxisForDataset(index);
    ValueAxis domainAxis = getDomainAxisForDataset(index);
    double domainMin = domainAxis.getLowerBound();
    double domainLength = domainAxis.getUpperBound() - domainMin;
    double rangeMin = rangeAxis.getLowerBound();
    double rangeLength = rangeAxis.getUpperBound() - rangeMin;
    int boxWidth = 6;

    double[][] data = (double[][]) series.get(index);

    double[] d1 = data[0];
    double[] d2 = data[1];
    int size = d1.length;

    Hashtable seen = new Hashtable();
    int lastX = 0;
    int lastY = 0;
    //TODO: Check for clipping
    //TODO: Try to create a GeneralPath with the points
    //and cal g2.draw just once
    GeneralPath path = new GeneralPath();
    long t1 = System.currentTimeMillis();

    for (int i = 0; i < size; i++) {
        int transX = (int) (xx + ww * (d1[i] - domainMin) / domainLength);
        int transY = (int) (yy - hh * (d2[i] - rangeMin) / rangeLength);
        Object key = transX + "_" + transY;
        if (seen.get(key) != null) {
            seenCnt++;
            continue;
        }
        seen.put(key, key);
        if (crosshairState != null) {
            crosshairState.updateCrosshairPoint(d1[i], d2[i], transX, transY, orientation);
        }

        switch (shape) {

        case LineState.SHAPE_VLINE:
            if (i > 1) {
                g2.drawLine(lastX, lastY, transX, transY);
            }
            lastX = transX;
            lastY = transY;

        case LineState.SHAPE_POINT:
            path.append(new Rectangle((int) transX, (int) transY, 1, 1), false);
            break;

        case LineState.SHAPE_LARGEPOINT:
            path.append(new Rectangle((int) transX, (int) transY, 2, 2), false);
            break;

        case LineState.SHAPE_RECTANGLE:
            path.append(
                    new Rectangle((int) transX - boxWidth / 2, (int) transY - boxWidth / 2, boxWidth, boxWidth),
                    false);
            break;

        case LineState.SHAPE_X:
            g2.drawLine(transX - boxWidth / 2, transY - boxWidth / 2, transX + boxWidth - boxWidth / 2,
                    transY + boxWidth - boxWidth / 2);
            g2.drawLine(transX + boxWidth - boxWidth / 2, transY - boxWidth / 2, transX - boxWidth / 2,
                    transY + boxWidth - boxWidth / 2);
            break;

        case LineState.SHAPE_PLUS:
            g2.drawLine(transX + boxWidth / 2, transY, transX + boxWidth / 2, transY + boxWidth);
            g2.drawLine(transX, transY + boxWidth / 2, transX + boxWidth, transY + boxWidth / 2);
            break;

        }
    }
    g2.fill(path);
    long t2 = System.currentTimeMillis();
    //        System.out.println ("time:" + (t2-t1));
    return true;
}

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

/**
 * Actually draws the environment on the view.
 * /*from w ww  .  j  a va2s  .  c  o  m*/
 * @param g
 *            {@link Graphics2D} object responsible for drawing
 */
protected final void drawEnvOnView(final Graphics2D g) {
    if (wormhole == null || !isVisible() || !isEnabled()) {
        return;
    }
    accessData();
    if (hooked.isPresent()) {
        final Position hcoor = positions.get(hooked.get());
        final Point hp = wormhole.getViewPoint(hcoor);
        if (hp.distance(getCenter()) > FREEDOM_RADIUS) {
            wormhole.setViewPosition(hp);
        }
    }
    /*
     * Compute nodes in sight and their screen position
     */
    final Map<Node<T>, Point> onView = positions.entrySet().parallelStream()
            .map(pair -> new Pair<>(pair.getKey(), wormhole.getViewPoint(pair.getValue())))
            .filter(p -> wormhole.isInsideView(p.getSecond()))
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    g.setColor(Color.BLACK);
    if (obstacles != null) {
        /*
         * TODO: only draw obstacles if on view
         */
        obstacles.parallelStream().map(this::convertObstacle).forEachOrdered(g::fill);
    }
    if (paintLinks) {
        g.setColor(Color.GRAY);
        onView.keySet().parallelStream().map(neighbors::get)
                .flatMap(neigh -> neigh.getNeighbors().parallelStream()
                        .map(node -> node.compareTo(neigh.getCenter()) > 0 ? new Pair<>(neigh.getCenter(), node)
                                : new Pair<>(node, neigh.getCenter())))
                .distinct().map(
                        pair -> mapPair(pair,
                                node -> Optional.ofNullable(onView.get(node))
                                        .orElse(wormhole.getViewPoint(positions.get(node)))))
                .forEachOrdered(line -> {
                    final Point p1 = line.getFirst();
                    final Point p2 = line.getSecond();
                    g.drawLine(p1.x, p1.y, p2.x, p2.y);
                });
    }
    releaseData();
    if (isDraggingMouse && status == ViewStatus.MOVING && originPoint.isPresent() && endingPoint.isPresent()) {
        for (final Node<T> n : selectedNodes) {
            if (onView.containsKey(n)) {
                onView.put(n, new Point(onView.get(n).x + (endingPoint.get().x - originPoint.get().x),
                        onView.get(n).y + (endingPoint.get().y - originPoint.get().y)));
            }
        }
    }
    g.setColor(Color.GREEN);
    if (effectStack != null) {
        effectStack.forEach(effect -> {
            onView.entrySet().forEach(entry -> {
                final Point p = entry.getValue();
                effect.apply(g, entry.getKey(), p.x, p.y);
            });
        });
    }
    if (isCloserNodeMarked()) {
        final Optional<Map.Entry<Node<T>, Point>> closest = onView.entrySet().parallelStream()
                .min((pair1, pair2) -> {
                    final Point p1 = pair1.getValue();
                    final Point p2 = pair2.getValue();
                    final double d1 = Math.hypot(p1.x - mousex, p1.y - mousey);
                    final double d2 = Math.hypot(p2.x - mousex, p2.y - mousey);
                    return Double.compare(d1, d2);
                });
        if (closest.isPresent()) {
            nearest = closest.get().getKey();
            final int nearestx = closest.get().getValue().x;
            final int nearesty = closest.get().getValue().y;
            drawFriedEgg(g, nearestx, nearesty, Color.RED, Color.YELLOW);
        }
    } else {
        nearest = null;
    }
    if (isDraggingMouse && status == ViewStatus.SELECTING && originPoint.isPresent()
            && endingPoint.isPresent()) {
        g.setColor(Color.BLACK);
        final int x = originPoint.get().x < endingPoint.get().x ? originPoint.get().x : endingPoint.get().x;
        final int y = originPoint.get().y < endingPoint.get().y ? originPoint.get().y : endingPoint.get().y;
        final int width = Math.abs(endingPoint.get().x - originPoint.get().x);
        final int height = Math.abs(endingPoint.get().y - originPoint.get().y);
        g.drawRect(x, y, width, height);
        selectedNodes = onView.entrySet().parallelStream()
                .filter(nodes -> isInsideRectangle(nodes.getValue(), x, y, width, height))
                .map(onScreen -> onScreen.getKey()).collect(Collectors.toSet());
    }
    selectedNodes.parallelStream().map(e -> Optional.ofNullable(onView.get(e))).filter(Optional::isPresent)
            .map(Optional::get).forEachOrdered(p -> drawFriedEgg(g, p.x, p.y, Color.BLUE, Color.CYAN));
}

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

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

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

    /* transients */
    if (!continua) {
        state = STATE_TRANSIENTS;//from   w w  w.j ava2s.co m

        for (int i = 0; i < stepperList.length; i++) {
            stepperList[i].initialize();
            prevX[i] = 0;
            prevY[i] = 0;
        }

        for (index = 0; index < transients; index++) {
            for (int i = 0; i < stepperList.length; i++) {
                stepperList[i].step();
            }
            if (stopped) {
                state = STATE_STOPPED;
                return;
            }
        }

        //            for (int i = 0; i < stepperList.length; i++) {
        //                stepperList[i].initialize();
        //                for (index = 0; index < transients; index++) {
        //                    stepperList[i].step();
        //                    if (stopped) {
        //                        state = STATE_STOPPED;
        //                        return;
        //                    }
        //                }
        //                prevX[i] = 0;
        //                prevY[i] = 0;
        //            }

        index = 0;
    }

    state = STATE_POINTS;

    Stepper.Point2D point;
    int x, y;
    int start = index;
    int end = 0;
    if (index == 0) {
        end = start + iterations + 1;
    } else {
        end = start + iterations;
    }

    Stroke stroke = new BasicStroke(7f);
    Stroke origStroke = g2.getStroke();
    Color color = Color.BLACK;

    for (; index < end; index++) {

        for (int i = 0; i < stepperList.length; i++) {
            point = stepperList[i].getCurrentPoint2D();

            if (!timePlot) {
                x = (int) domainAxis.valueToJava2D(point.getX(), dataArea, RectangleEdge.BOTTOM);
            } else {
                x = (int) domainAxis.valueToJava2D(index + transients, dataArea, RectangleEdge.BOTTOM);
            }

            y = (int) rangeAxis.valueToJava2D(point.getY(), dataArea, RectangleEdge.LEFT);

            g2.setPaint(paintList[i]);

            if (connectWithLines) {
                if (index > 0) {
                    g2.drawLine(x, y, prevX[i], prevY[i]);
                }

                prevX[i] = x;
                prevY[i] = y;
            }

            if (bigDots) {
                g2.fillRect(x - 1, y - 1, 3, 3);
            } else {
                g2.fillRect(x, y, 1, 1);
            }

            stepperList[i].step();
        }

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

        if (delay > 0) {
            try {
                Thread.sleep(delay);
            } catch (final InterruptedException e) {
            } finally {
            }
        }

    }
    state = STATE_FINISHED;
}

From source file:org.tellervo.desktop.graph.SkeletonPlot.java

public void draw(GraphSettings gInfo, Graphics2D g2, int bottom, Graph g, int thickness, int xscroll) {
    // cache yearsize, we use this a lot
    int yearWidth = gInfo.getYearWidth(); // the size of a year, in pixels
    float unitScale = gInfo.getHundredUnitHeight() / 100.0f; // the size of 1 "unit" in pixels.

    // set pen/* ww  w . j  av a 2  s. c  o  m*/
    boolean dotted = (gInfo.isDottedIndexes() && (g.graph instanceof Index));
    g2.setStroke(makeStroke(thickness, dotted));

    // If it's a chronology, point bones down
    /*if(g.graph instanceof Sample)
    {
       if (((Sample) g.graph).getSeries() instanceof TridasDerivedSeries)
       {
    this.areBonesBelowLine = true;
       }
    }*/

    // left/right
    int l = g2.getClipBounds().x;
    int r = l + g2.getClipBounds().width;

    // no data?  stop.
    if (g.graph.getRingWidthData().isEmpty())
        return;

    // compare g.getClipBounds() to [x,0]..[x+yearSize*data.size(),bottom]
    tempRect.x = yearWidth * (g.graph.getStart().diff(gInfo.getDrawBounds().getStart()) + g.xoffset); // REDUNDANT! see x later
    tempRect.y = 0; // - g.yoffset, IF you're sure there are no negative values (but there are)
    tempRect.width = yearWidth * (g.graph.getRingWidthData().size() - 1);
    tempRect.height = bottom;
    // TODO: compute top/bottom as min/max?
    // REFACTOR: will this be obsolete with the start/end stuff below?
    if (!tempRect.intersects(g2.getClipBounds())) {
        // skip this graph, it's off the screen
        return;
    }

    // Draw standard line
    int x = yearWidth * (g.graph.getStart().diff(gInfo.getDrawBounds().getStart()) + g.xoffset);
    //int value1 = yTransform((float) getMeanValue(g));
    int value1 = yTransform((float) baselineY);
    int baseYVal = bottom - (int) (value1 * unitScale) - (int) (g.yoffset * unitScale);

    try {
        // x-position
        int x1 = x;
        int x2 = yearWidth * (g.graph.getStart().diff(gInfo.getDrawBounds().getStart()) + g.xoffset
                + g.graph.getRingWidthData().size());

        // if we're past the end, draw only as far as we need
        if (x2 > r + yearWidth) {
            x2 = r + yearWidth;
        }

        //log.debug("Drawing mean line: "+x1+", "+meanYVal+", "+x2+", "+meanYVal);
        g2.drawLine(x1, baseYVal, x2, baseYVal);

        // Calcs for start/end triangles
        int YLineHeight = 50;
        int YTriangleHeight = 25;
        int XTriangleWidth = 15;
        if (areBonesBelowLine) {
            YLineHeight = -50;
            YTriangleHeight = -25;
        }

        // Draw start triangle
        g2.drawLine(x1, baseYVal, x1, baseYVal - YTriangleHeight);
        g2.drawLine(x1, baseYVal, x1 - XTriangleWidth, baseYVal - YTriangleHeight);
        g2.drawLine(x1 - XTriangleWidth, baseYVal - YTriangleHeight, x1, baseYVal - YTriangleHeight);
        g2.drawLine(x1, baseYVal, x1, baseYVal - YLineHeight);

        // Draw end triangle
        g2.drawLine(x2, baseYVal, x2, baseYVal - YTriangleHeight);
        g2.drawLine(x2, baseYVal, x2 + XTriangleWidth, baseYVal - YTriangleHeight);
        g2.drawLine(x2 + XTriangleWidth, baseYVal - YTriangleHeight, x2, baseYVal - YTriangleHeight);
        g2.drawLine(x2, baseYVal, x2, baseYVal - YLineHeight);

    } catch (ClassCastException cce) {

    }

    int value;
    try {
        value = ((Number) g.graph.getRingWidthData().get(0)).intValue();
        value = yTransform(value * g.scale);
    } catch (ClassCastException cce) {
        value = yTransform(0);
    }

    int n = g.graph.getRingWidthData().size();

    for (int i = 1; i < n; i++) {
        // new x-position for this point
        x += yearWidth;

        // if we're past the end, draw what we've got, and say goodbye
        // (go +_yearsize so the line going off the screen is visible)
        if (x > r + yearWidth) {
            break;
        }

        // Extract the window of interest
        int ringsEitherSideOfFocus = (App.prefs.getIntPref(PrefKey.STATS_SKELETON_PLOT_WINDOW_SIZE, 7) - 1) / 2;

        // Convert to ArrayList first as its easier to handle
        ArrayList<Double> ringWidths = new ArrayList<Double>();
        for (int z = 0; z < n; z++) {
            ringWidths.add((double) g.graph.getRingWidthData().get(z).intValue());
        }

        int firstind = i - 1 - ringsEitherSideOfFocus;
        int lastind = i + ringsEitherSideOfFocus;
        if (firstind < 0)
            firstind = 0;
        if (lastind > n)
            lastind = n;
        int size = lastind - firstind;

        double[] window = new double[size];

        int t = 0;
        for (int w = firstind; w < lastind; w++) {
            window[t] = ringWidths.get(w);
            t++;
        }

        DescriptiveStatistics windowStats = new DescriptiveStatistics(window);
        /*if(i<7 ) 
        {
           log.debug("Stats for ring: "+i);
           try{
              log.debug("  Window 0: "+window[0]);
              log.debug("  Window 1: "+window[1]);
              log.debug("  Window 2: "+window[2]);
              log.debug("  Window 3: "+window[3]);
              log.debug("  Window 4: "+window[4]);
              log.debug("  Window 5: "+window[5]);
              log.debug("  Window 6: "+window[6]);
           } catch (ArrayIndexOutOfBoundsException e){}
           log.debug("  Mean  is "+i+" - "+(int) windowStats.getMean());
           log.debug("  Min   is "+i+" - "+(int) windowStats.getMin());
           log.debug("  Std   is "+i+" - "+(int) windowStats.getStandardDeviation());
           log.debug("  Std/2 is "+i+" - "+(int) windowStats.getStandardDeviation()/2);
        }*/

        // y-position for this point
        try {
            value = yTransform(((Number) g.graph.getRingWidthData().get(i)).intValue() * g.scale);
        } catch (ClassCastException cce) {
            value = yTransform(0); // e.g., if it's being edited, it's still a string
            // BAD!  instead: (1) draw what i've got so far, and (2) NEXT point is a move-to.
            // -- try to parse String as an integer?
        }
        int y = bottom - (int) (value * unitScale) - (int) (g.yoffset * unitScale);

        // Calculate skeleton category
        Integer skeletonCateogory = null;

        String prefAlg = App.prefs.getPref(PrefKey.STATS_SKELETON_PLOT_ALGORITHM,
                SkeletonPlotAlgorithm.PERCENTILES.toString());

        if (prefAlg.equals(SkeletonPlotAlgorithm.PERCENTILES.toString())) {
            skeletonCateogory = getSkeletonCategoryFromPercentiles(value, windowStats);
        } else if (prefAlg.equals(SkeletonPlotAlgorithm.CROPPER1979_0POINT5.toString())) {
            skeletonCateogory = getSkeletonCategoryFromCropper1979(value, windowStats, 0.5);
        } else if (prefAlg.equals(SkeletonPlotAlgorithm.CROPPER1979_0POINT75.toString())) {
            skeletonCateogory = getSkeletonCategoryFromCropper1979(value, windowStats, 0.75);
        }

        // Draw the skeleton line
        if (areBonesBelowLine) {
            g2.drawLine(x, baseYVal, x, baseYVal + (skeletonCateogory * 5));
        } else {
            g2.drawLine(x, baseYVal, x, baseYVal - (skeletonCateogory * 5));
        }

        // Try and paint remark icons
        try {
            List<TridasRemark> remarks = g.graph.getTridasValues().get(i).getRemarks();

            if (areBonesBelowLine) {
                Graph.drawRemarkIcons(g2, gInfo, remarks, g.graph.getTridasValues().get(i), x, baseYVal, false);
            } else {
                Graph.drawRemarkIcons(g2, gInfo, remarks, g.graph.getTridasValues().get(i), x, baseYVal, true);
            }

        } catch (Exception e) {
            log.error("Exception drawing icons to graph: " + e.getClass());
        }

    }
}

From source file:com.projity.pm.graphic.gantt.GanttRenderer.java

public void paintNonWorkingDays(Graphics2D g2, Rectangle bounds) {
    BarFormat calFormat = getCalendarFormat();
    if (calFormat == null)
        return;//  w w  w .  j av  a 2s.  co m
    //non working days
    Color oldColor = g2.getColor();
    Paint oldPaint = g2.getPaint();
    CoordinatesConverter coord = ((GanttParams) graphInfo).getCoord();
    Project project = coord.getProject();
    WorkingCalendar wc = (WorkingCalendar) project.getWorkCalendar();

    if (coord.getTimescaleManager().isShowWholeDays()) {
        boolean useScale2 = coord.getTimescaleManager().getCurrentScaleIndex() == 0; //valid only for current time scales
        TimeIterator i = coord.getTimeIterator(bounds.getX(), bounds.getMaxX(), useScale2);
        long startNonworking = -1L, endNonWorking = -1L;
        Calendar cal = DateTime.calendarInstance();

        PredefinedPaint paint = (PredefinedPaint) calFormat.getMiddle().getPaint();//new PredefinedPaint(PredefinedPaint.DOT_LINE,Colors.VERY_LIGHT_GRAY,Color.WHITE);
        paint.applyPaint(g2, useTextures());
        while (i.hasNext()) {
            TimeInterval interval = i.next();
            long s = interval.getStart();
            if (CalendarService.getInstance().getDay(wc, s).isWorking()) {
                if (startNonworking != -1L) {
                    drawNonWorking(g2, startNonworking, endNonWorking, cal, coord, bounds, useScale2);
                    startNonworking = endNonWorking = -1L;
                }
            } else {
                if (startNonworking == -1L)
                    startNonworking = s;
                endNonWorking = s;

            }
        }
        if (startNonworking != -1L) {
            drawNonWorking(g2, startNonworking, endNonWorking, cal, coord, bounds, useScale2);
            startNonworking = endNonWorking = -1L;
        }
    }

    if (container != null) {
        //scale2 separation lines
        TimeIterator i = coord.getTimeIterator(bounds.getX(), bounds.getMaxX(), true);
        g2.setPaint(new PredefinedPaint(PredefinedPaint.DOT_LINE2, Color.GRAY, g2.getBackground()));
        while (i.hasNext()) {
            TimeInterval interval = i.next();
            int startX = (int) Math.round(coord.toX(interval.getStart()));
            g2.drawLine(startX, bounds.y, startX, bounds.y + bounds.height);
        }

        //project start
        int projectStartX = (int) Math.round(coord.toX(project.getStart()));
        if (projectStartX >= bounds.getX() && projectStartX <= bounds.getMaxX()) {
            g2.setPaint(new PredefinedPaint(PredefinedPaint.DASH_LINE, Color.GRAY, g2.getBackground()));
            g2.drawLine(projectStartX, bounds.y, projectStartX, bounds.y + bounds.height);
        }

        //project start
        long statusDate = project.getStatusDate();
        if (statusDate != 0) {
            int statusDateX = (int) Math.round(coord.toX(statusDate));
            if (statusDateX >= bounds.getX() && statusDateX <= bounds.getMaxX()) {
                g2.setPaint(new PredefinedPaint(PredefinedPaint.DOT_LINE2, Color.GREEN, g2.getBackground()));
                g2.drawLine(statusDateX, bounds.y, statusDateX, bounds.y + bounds.height);
            }
        }

        if (oldColor != null)
            g2.setColor(oldColor);
        if (oldPaint != null)
            g2.setPaint(oldPaint);

    }
}