Example usage for java.awt Graphics2D setStroke

List of usage examples for java.awt Graphics2D setStroke

Introduction

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

Prototype

public abstract void setStroke(Stroke s);

Source Link

Document

Sets the Stroke for the Graphics2D context.

Usage

From source file:org.ietr.preesm.mapper.ui.MyGanttRenderer.java

/**
 * Draws the tasks/subtasks for one item.
 * /*  w  w  w  . ja va2  s .  c  om*/
 * @param g2
 *            the graphics device.
 * @param state
 *            the renderer state.
 * @param dataArea
 *            the data plot area.
 * @param plot
 *            the plot.
 * @param domainAxis
 *            the domain axis.
 * @param rangeAxis
 *            the range axis.
 * @param dataset
 *            the data.
 * @param row
 *            the row index (zero-based).
 * @param column
 *            the column index (zero-based).
 */
@Override
protected void drawTasks(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea,
        CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, GanttCategoryDataset dataset, int row,
        int column) {

    int count = dataset.getSubIntervalCount(row, column);
    if (count == 0) {
        drawTask(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column);
    }

    for (int subinterval = 0; subinterval < count; subinterval++) {

        RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge();

        // value 0
        Number value0 = dataset.getStartValue(row, column, subinterval);
        if (value0 == null) {
            return;
        }
        double translatedValue0 = rangeAxis.valueToJava2D(value0.doubleValue(), dataArea, rangeAxisLocation);

        // value 1
        Number value1 = dataset.getEndValue(row, column, subinterval);
        if (value1 == null) {
            return;
        }
        double translatedValue1 = rangeAxis.valueToJava2D(value1.doubleValue(), dataArea, rangeAxisLocation);

        if (translatedValue1 < translatedValue0) {
            double temp = translatedValue1;
            translatedValue1 = translatedValue0;
            translatedValue0 = temp;
        }

        double rectStart = calculateBarW0(plot, plot.getOrientation(), dataArea, domainAxis, state, row,
                column);
        double rectLength = Math.abs(translatedValue1 - translatedValue0);
        double rectBreadth = state.getBarWidth();

        // DRAW THE BARS...
        RoundRectangle2D bar = null;

        bar = new RoundRectangle2D.Double(translatedValue0, rectStart, rectLength, rectBreadth, 10.0, 10.0);

        /* Paint seriesPaint = */getItemPaint(row, column);

        if (((TaskSeriesCollection) dataset).getSeriesCount() > 0)
            if (((TaskSeriesCollection) dataset).getSeries(0).getItemCount() > column)
                if (((TaskSeriesCollection) dataset).getSeries(0).get(column).getSubtaskCount() > subinterval) {
                    g2.setPaint(getRandomBrightColor(((TaskSeriesCollection) dataset).getSeries(0).get(column)
                            .getSubtask(subinterval).getDescription()));

                }
        g2.fill(bar);

        if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) {
            g2.setStroke(getItemStroke(row, column));
            g2.setPaint(getItemOutlinePaint(row, column));
            g2.draw(bar);
        }

        // Displaying the tooltip inside the bar if enough space is
        // available
        if (getToolTipGenerator(row, column) != null) {
            // Getting the string to display
            String tip = getToolTipGenerator(row, column).generateToolTip(dataset, subinterval, column);

            // Truncting the string if it is too long
            String subtip = "";
            if (rectLength > 0) {
                double percent = (g2.getFontMetrics().getStringBounds(tip, g2).getWidth() + 10) / rectLength;

                if (percent > 1.0) {
                    subtip = tip.substring(0, (int) (tip.length() / percent));
                } else if (percent > 0) {
                    subtip = tip;
                }

                // Setting font and color
                Font font = new Font("Garamond", Font.BOLD, 12);
                g2.setFont(font);
                g2.setColor(Color.WHITE);

                // Testing width and displaying
                if (!subtip.isEmpty()) {
                    g2.drawString(subtip, (int) translatedValue0 + 5,
                            (int) rectStart + g2.getFontMetrics().getHeight());
                }
            }
        }

        // collect entity and tool tip information...
        if (state.getInfo() != null) {
            EntityCollection entities = state.getEntityCollection();
            if (entities != null) {
                String tip = null;
                if (getToolTipGenerator(row, column) != null) {
                    tip = getToolTipGenerator(row, column).generateToolTip(dataset, subinterval, column);
                }
                String url = null;
                if (getItemURLGenerator(row, column) != null) {
                    url = getItemURLGenerator(row, column).generateURL(dataset, row, column);
                }
                CategoryItemEntity entity = new CategoryItemEntity(bar, tip, url, dataset,
                        dataset.getRowKey(row), dataset.getColumnKey(column));
                entities.add(entity);
            }
        }
    }

}

From source file:extern.NpairsBoxAndWhiskerRenderer.java

/**
 * Draws the visual representation of a single data item when the plot has
 * a horizontal orientation.//from  w  ww.  jav a 2  s . com
 *
 * @param g2  the graphics device.
 * @param state  the renderer state.
 * @param dataArea  the area within which the plot is being drawn.
 * @param plot  the plot (can be used to obtain standard color
 *              information etc).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset (must be an instance of
 *                 {@link BoxAndWhiskerCategoryDataset}).
 * @param row  the row index (zero-based).
 * @param column  the column index (zero-based).
 */
public void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea,
        CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row,
        int column) {

    BoxAndWhiskerCategoryDataset bawDataset = (BoxAndWhiskerCategoryDataset) dataset;

    double categoryEnd = domainAxis.getCategoryEnd(column, getColumnCount(), dataArea,
            plot.getDomainAxisEdge());
    double categoryStart = domainAxis.getCategoryStart(column, getColumnCount(), dataArea,
            plot.getDomainAxisEdge());
    double categoryWidth = Math.abs(categoryEnd - categoryStart);

    double yy = categoryStart;
    int seriesCount = getRowCount();
    int categoryCount = getColumnCount();

    double widthWeWannaUse = Math.min(state.getBarWidth(), dataArea.getWidth() / 10);

    if (seriesCount > 1) {
        double seriesGap = dataArea.getHeight() * getItemMargin() / (categoryCount * (seriesCount - 1));
        //            double usedWidth = (state.getBarWidth() * seriesCount)
        //                               + (seriesGap * (seriesCount - 1));
        double usedWidth = (widthWeWannaUse * seriesCount) + (seriesGap * (seriesCount - 1));
        // offset the start of the boxes if the total width used is smaller
        // than the category width
        double offset = (categoryWidth - usedWidth) / 2;
        //            yy = yy + offset + (row * (state.getBarWidth() + seriesGap));
        yy = yy + offset + (row * (widthWeWannaUse + seriesGap));
    } else {
        // offset the start of the box if the box width is smaller than
        // the category width
        //            double offset = (categoryWidth - state.getBarWidth()) / 2;
        double offset = (categoryWidth - widthWeWannaUse) / 2;
        yy = yy + offset;
    }

    g2.setPaint(getItemPaint(row, column));
    Stroke s = getItemStroke(row, column);
    g2.setStroke(s);

    RectangleEdge location = plot.getRangeAxisEdge();

    Number xQ1 = bawDataset.getQ1Value(row, column);
    Number xQ3 = bawDataset.getQ3Value(row, column);
    Number xMax = bawDataset.getMaxRegularValue(row, column);
    Number xMin = bawDataset.getMinRegularValue(row, column);

    Shape box = null;
    if (xQ1 != null && xQ3 != null && xMax != null && xMin != null) {

        double xxQ1 = rangeAxis.valueToJava2D(xQ1.doubleValue(), dataArea, location);
        double xxQ3 = rangeAxis.valueToJava2D(xQ3.doubleValue(), dataArea, location);
        double xxMax = rangeAxis.valueToJava2D(xMax.doubleValue(), dataArea, location);
        double xxMin = rangeAxis.valueToJava2D(xMin.doubleValue(), dataArea, location);
        //            double yymid = yy + state.getBarWidth() / 2.0;
        double yymid = yy + widthWeWannaUse / 2.0;

        // draw the upper shadow...
        g2.draw(new Line2D.Double(xxMax, yymid, xxQ3, yymid));
        //            g2.draw(new Line2D.Double(xxMax, yy, xxMax,
        //                    yy + state.getBarWidth()));
        g2.draw(new Line2D.Double(xxMax, yy, xxMax, yy + widthWeWannaUse));

        // draw the lower shadow...
        g2.draw(new Line2D.Double(xxMin, yymid, xxQ1, yymid));
        //            g2.draw(new Line2D.Double(xxMin, yy, xxMin,
        //                    yy + state.getBarWidth()));
        g2.draw(new Line2D.Double(xxMin, yy, xxMin, yy + widthWeWannaUse));

        // draw the box...
        //            box = new Rectangle2D.Double(Math.min(xxQ1, xxQ3), yy,
        //                    Math.abs(xxQ1 - xxQ3), state.getBarWidth());
        box = new Rectangle2D.Double(Math.min(xxQ1, xxQ3), yy, Math.abs(xxQ1 - xxQ3), widthWeWannaUse);
        if (this.fillBox) {
            g2.fill(box);
        }
        g2.setStroke(getItemOutlineStroke(row, column));
        g2.setPaint(getItemOutlinePaint(row, column));
        g2.draw(box);
    }

    g2.setPaint(this.artifactPaint);
    double aRadius = 0; // average radius

    // draw mean - SPECIAL AIMS REQUIREMENT...
    Number xMean = bawDataset.getMeanValue(row, column);
    if (xMean != null) {
        double xxMean = rangeAxis.valueToJava2D(xMean.doubleValue(), dataArea, location);
        //            aRadius = state.getBarWidth() / 4;
        aRadius = widthWeWannaUse / 4;
        // here we check that the average marker will in fact be visible
        // before drawing it...
        if ((xxMean > (dataArea.getMinX() - aRadius)) && (xxMean < (dataArea.getMaxX() + aRadius))) {
            Ellipse2D.Double avgEllipse = new Ellipse2D.Double(xxMean - aRadius, yy + aRadius, aRadius * 2,
                    aRadius * 2);
            g2.fill(avgEllipse);
            g2.draw(avgEllipse);
        }
    }

    // draw median...
    Number xMedian = bawDataset.getMedianValue(row, column);
    if (xMedian != null) {
        double xxMedian = rangeAxis.valueToJava2D(xMedian.doubleValue(), dataArea, location);
        //            g2.draw(new Line2D.Double(xxMedian, yy, xxMedian,
        //                    yy + state.getBarWidth()));
        g2.draw(new Line2D.Double(xxMedian, yy, xxMedian, yy + widthWeWannaUse));
    }

    // collect entity and tool tip information...
    if (state.getInfo() != null && box != null) {
        EntityCollection entities = state.getEntityCollection();
        if (entities != null) {
            addItemEntity(entities, dataset, row, column, box);
        }
    }

}

From source file:org.jfree.chart.demo.ExtendedStackedBarRenderer.java

/**
 * Draws a stacked bar for a specific item.
 *
 * @param g2  the graphics device./*from  www  .  java 2  s  .  com*/
 * @param state  the renderer state.
 * @param dataArea  the plot area.
 * @param plot  the plot.
 * @param domainAxis  the domain (category) axis.
 * @param rangeAxis  the range (value) axis.
 * @param dataset  the data.
 * @param row  the row index (zero-based).
 * @param column  the column index (zero-based).
 */
public void drawItem(final Graphics2D g2, final CategoryItemRendererState state, final Rectangle2D dataArea,
        final CategoryPlot plot, final CategoryAxis domainAxis, final ValueAxis rangeAxis,
        final CategoryDataset dataset, final int row, final int column) {

    // nothing is drawn for null values...
    final Number dataValue = dataset.getValue(row, column);
    if (dataValue == null) {
        return;
    }

    final double value = dataValue.doubleValue();

    final PlotOrientation orientation = plot.getOrientation();
    final double barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea,
            plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0;

    double positiveBase = 0.0;
    double negativeBase = 0.0;

    for (int i = 0; i < row; i++) {
        final Number v = dataset.getValue(i, column);
        if (v != null) {
            final double d = v.doubleValue();
            if (d > 0) {
                positiveBase = positiveBase + d;
            } else {
                negativeBase = negativeBase + d;
            }
        }
    }

    final double translatedBase;
    final double translatedValue;
    final RectangleEdge location = plot.getRangeAxisEdge();
    if (value > 0.0) {
        translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea, location);
        translatedValue = rangeAxis.valueToJava2D(positiveBase + value, dataArea, location);
    } else {
        translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea, location);
        translatedValue = rangeAxis.valueToJava2D(negativeBase + value, dataArea, location);
    }
    final double barL0 = Math.min(translatedBase, translatedValue);
    final double barLength = Math.max(Math.abs(translatedValue - translatedBase), getMinimumBarLength());

    Rectangle2D bar = null;
    if (orientation == PlotOrientation.HORIZONTAL) {
        bar = new Rectangle2D.Double(barL0, barW0, barLength, state.getBarWidth());
    } else {
        bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(), barLength);
    }
    final Paint seriesPaint = getItemPaint(row, column);
    g2.setPaint(seriesPaint);
    g2.fill(bar);
    if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) {
        g2.setStroke(getItemStroke(row, column));
        g2.setPaint(getItemOutlinePaint(row, column));
        g2.draw(bar);
    }

    //        final CategoryLabelGenerator generator = getLabelGenerator(row, column);
    //      if (generator != null && isItemLabelVisible(row, column)) {
    //        drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0));
    //  }       

    if (value > 0.0) {
        if (this.showPositiveTotal) {
            if (isLastPositiveItem(dataset, row, column)) {
                g2.setPaint(Color.black);
                g2.setFont(this.totalLabelFont);
                final double total = calculateSumOfPositiveValuesForCategory(dataset, column);
                //            RefineryUtilities.drawRotatedString(
                //              this.totalFormatter.format(total), g2,
                //            (float) bar.getCenterX(),
                //          (float) (bar.getMinY() - 4.0), 
                ///        TextAnchor.BOTTOM_CENTER, 
                //         TextAnchor.BOTTOM_CENTER, 
                //       0.0
                // );              
            }
        }
    } else {
        if (this.showNegativeTotal) {
            if (isLastNegativeItem(dataset, row, column)) {
                g2.setPaint(Color.black);
                g2.setFont(this.totalLabelFont);
                final double total = calculateSumOfNegativeValuesForCategory(dataset, column);
                /*                    RefineryUtilities.drawRotatedString(
                String.valueOf(total), g2,
                (float) bar.getCenterX(),
                (float) (bar.getMaxY() + 4.0), 
                TextAnchor.TOP_CENTER, 
                TextAnchor.TOP_CENTER, 
                0.0
                                    );              
                  */ }
        }
    }

    // collect entity and tool tip information...
    if (state.getInfo() != null) {
        final EntityCollection entities = state.getInfo().getOwner().getEntityCollection();
        if (entities != null) {
            String tip = null;
            final CategoryToolTipGenerator tipster = getToolTipGenerator(row, column);
            if (tipster != null) {
                tip = tipster.generateToolTip(dataset, row, column);
            }
            String url = null;
            if (getItemURLGenerator(row, column) != null) {
                url = getItemURLGenerator(row, column).generateURL(dataset, row, column);
            }
            final CategoryItemEntity entity = new CategoryItemEntity(bar, tip, url, dataset, row,
                    dataset.getColumnKey(column), column);
            //            entities.addEntity(entity);
        }
    }

}

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

public void render(final Graphics2D g2, final Rectangle2D dataArea, final PlotRenderingInfo info) {
    ValueAxis domainAxis = plot.getDomainAxis();
    ValueAxis rangeAxis = plot.getRangeAxis();

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

    /* transients */
    if (!continua) {
        stepper.initialize();/*  w  w  w  .  j a v  a 2 s  .c  om*/

        state = STATE_TRANSIENTS;

        try {
            for (index = 0; index < transients; index++) {
                stepper.step();
                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }
            }
        } catch (RuntimeException re) {
            throw new RuntimeException(re);
        }

        index = 0;
        prevX = 0;
        prevY = 0;
    }

    state = STATE_POINTS;

    Stepper.Point2D point;
    double[] fullPoint = new double[dataset.getNcol()];
    dataset.clearRows();
    int x, y;
    int start = index;
    int end = 0;
    if (index == 0) {
        end = start + iterations + 1;
    } else {
        end = start + iterations;
    }

    for (; index < end; index++) {
        point = stepper.getCurrentPoint2D();
        stepper.getCurrentValue(fullPoint);
        try {
            dataset.addRow((double[]) fullPoint.clone());
        } catch (DatasetException e) {
            System.err.println(e);
        }

        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);

        if (Double.isNaN(point.getX()) || Double.isNaN(point.getY())) {
            System.err.println("NaN values at iteration " + index);
            //FIXME
            //Don't simply throw exception: that would mess up the state machine!
            //throw new RuntimeException("NaN values at iteration " + index);
        }

        if (delay > 0) {
            boolean flag = false;

            try {
                Thread.sleep(delay * 5);

                drawItem(g2, index, x, y);

                g2.setXORMode(color);
                g2.setStroke(stroke);
                g2.drawRect(x - 1, y - 1, 3, 3);

                flag = true;

                Thread.sleep(delay * 5);
            } catch (final InterruptedException e) {
            }

            if (flag) {
                g2.drawRect(x - 1, y - 1, 3, 3);
                g2.setPaintMode();
                g2.setStroke(origStroke);
            } else {
                drawItem(g2, index, x, y);
            }
        } else {
            drawItem(g2, index, x, y);
        }

        try {
            stepper.step();
        } catch (RuntimeException re) {
            throw new RuntimeException(re);
        }

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

    state = STATE_FINISHED;
}

From source file:longMethod.jfreechart.drawItem.SamplingXYLineRenderer.java

/**
 * Draws the visual representation of a single data item.
 *
 * @param g2  the graphics device.//from  ww  w  . jav a2  s.  c o m
 * @param state  the renderer state.
 * @param dataArea  the area within which the data is being drawn.
 * @param info  collects information about the drawing.
 * @param plot  the plot (can be used to obtain standard color
 *              information etc).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset.
 * @param series  the series index (zero-based).
 * @param item  the item index (zero-based).
 * @param crosshairState  crosshair information for the plot
 *                        (<code>null</code> permitted).
 * @param pass  the pass index.
 */
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) {

    // do nothing if item is not visible
    if (!getItemVisible(series, item)) {
        return;
    }
    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();

    // get the data point...
    double x1 = dataset.getXValue(series, item);
    double y1 = dataset.getYValue(series, item);
    double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

    State s = (State) state;
    // update path to reflect latest point
    if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
        float x = (float) transX1;
        float y = (float) transY1;
        PlotOrientation orientation = plot.getOrientation();
        if (orientation == PlotOrientation.HORIZONTAL) {
            x = (float) transY1;
            y = (float) transX1;
        }
        if (s.lastPointGood) {
            if ((Math.abs(x - s.lastX) > s.dX)) {
                s.seriesPath.lineTo(x, y);
                if (s.lowY < s.highY) {
                    s.intervalPath.moveTo((float) s.lastX, (float) s.lowY);
                    s.intervalPath.lineTo((float) s.lastX, (float) s.highY);
                }
                s.lastX = x;
                s.openY = y;
                s.highY = y;
                s.lowY = y;
                s.closeY = y;
            } else {
                s.highY = Math.max(s.highY, y);
                s.lowY = Math.min(s.lowY, y);
                s.closeY = y;
            }
        } else {
            s.seriesPath.moveTo(x, y);
            s.lastX = x;
            s.openY = y;
            s.highY = y;
            s.lowY = y;
            s.closeY = y;
        }
        s.lastPointGood = true;
    } else {
        s.lastPointGood = false;
    }
    // if this is the last item, draw the path ...
    if (item == s.getLastItemIndex()) {
        // draw path
        PathIterator pi = s.seriesPath.getPathIterator(null);
        int count = 0;
        while (!pi.isDone()) {
            count++;
            pi.next();
        }
        g2.setStroke(getItemStroke(series, item));
        g2.setPaint(getItemPaint(series, item));
        g2.draw(s.seriesPath);
        g2.draw(s.intervalPath);
    }
}

From source file:org.pmedv.blackboard.components.BoardEditor.java

/**
 * Draws the selected item to the graphics context
 * /* ww  w .  ja  v a 2  s  .c  om*/
 * @param layer the layer to be drawn
 * @param g2d the graphics context
 */
private void drawLayer(Layer layer, Graphics2D g2d) {
    if (!layer.isVisible())
        return;

    DefaultTransformModel xmodel = null;

    if (zoomLayer != null) {
        TransformUI ui = (TransformUI) (Object) zoomLayer.getUI();
        xmodel = (DefaultTransformModel) ui.getModel();
    }

    if (layer.getName().equalsIgnoreCase("board")) {
        if (backgroundImage != null) {
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, layer.getOpacity()));
            g2d.drawImage(backgroundImage, 0, 0, this);
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        } else {
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }

        g2d.setColor(Color.LIGHT_GRAY);
        g2d.setStroke(BoardUtil.stroke_1_0f);

        Boolean dotGrid = (Boolean) Preferences.values
                .get("org.pmedv.blackboard.BoardDesignerPerspective.dotGrid");
        // draw grid
        if (gridVisible) {
            BoardUtil.drawGrid(g2d, raster, model.getWidth(), model.getHeight(), dotGrid.booleanValue());
        }

        return;
    }

    if (layer.getName().equalsIgnoreCase("ratsnest")) {
        if (layer.getImage() != null) {
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, layer.getOpacity()));
            g2d.drawImage(layer.getImage(), 0, 0, this);
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        }
        return;
    }

    for (Item item : layer.getItems()) {

        if (xmodel != null)
            item.setMirror(xmodel.isMirror());

        item.setOpacity(layer.getOpacity());

        if (item instanceof Line) {
            Line line = (Line) item;
            if (line.getStroke() != null)
                g2d.setStroke(line.getStroke());
            else
                g2d.setStroke(BoardUtil.stroke_3_0f);
            g2d.setColor(item.getColor());
        }

        item.draw(g2d);

        if (selectedItems.contains(item)) {
            g2d.setColor(Color.GREEN);
            g2d.setStroke(BoardUtil.stroke_1_0f);
            item.drawHandles(g2d, 8);
        }
    }
}

From source file:net.sf.maltcms.chromaui.charts.renderer.XYNoBlockRenderer.java

/**
 * Draws the block representing the specified item.
 *
 * @param g2 the graphics device.//from  w  w  w  .  j a va  2s .c  om
 * @param state the state.
 * @param dataArea the data area.
 * @param info the plot rendering info.
 * @param plot the plot.
 * @param domainAxis the x-axis.
 * @param rangeAxis the y-axis.
 * @param dataset the dataset.
 * @param series the series index.
 * @param item the item index.
 * @param crosshairState the crosshair state.
 * @param pass the pass index.
 */
@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;
    double x = dataset.getXValue(series, item);
    double y = dataset.getYValue(series, item);
    double z = 0.0;
    if (dataset instanceof XYZDataset) {
        z = ((XYZDataset) dataset).getZValue(series, item);
        if (entityThreshold != Double.NaN && z < entityThreshold) {
            return;
        }
    }

    //}
    Paint p = getPaintScale().getPaint(z);
    //        if(p.equals(getPaintScale().getPaint(getPaintScale().getLowerBound()))) {
    //            return;
    //        }
    //        double xx0 = domainAxis.valueToJava2D(x + xOffset, dataArea,
    //                plot.getDomainAxisEdge());
    //        double yy0 = rangeAxis.valueToJava2D(y + yOffset, dataArea,
    //                plot.getRangeAxisEdge());
    //        double xx1 = domainAxis.valueToJava2D(x + blockWidth
    //                + xOffset, dataArea, plot.getDomainAxisEdge());
    //        double yy1 = rangeAxis.valueToJava2D(y + blockHeight
    //                + yOffset, dataArea, plot.getRangeAxisEdge());
    double xx0 = domainAxis.valueToJava2D(x - getBlockWidth() / 2, dataArea, plot.getDomainAxisEdge());
    double yy0 = rangeAxis.valueToJava2D(y - getBlockHeight() / 2, dataArea, plot.getRangeAxisEdge());
    double xx1 = domainAxis.valueToJava2D(x + getBlockWidth() / 2, dataArea, plot.getDomainAxisEdge());
    double yy1 = rangeAxis.valueToJava2D(y + getBlockHeight() / 2, dataArea, plot.getRangeAxisEdge());

    Rectangle2D block;
    PlotOrientation orientation = plot.getOrientation();
    if (orientation.equals(PlotOrientation.HORIZONTAL)) {
        if (dataArea.contains(Math.min(yy0, yy1), Math.min(xx0, xx1), Math.abs(yy1 - yy0),
                Math.abs(xx0 - xx1))) {
            block = new Rectangle2D.Double(Math.min(yy0, yy1), Math.min(xx0, xx1), Math.abs(yy1 - yy0),
                    Math.abs(xx0 - xx1));
        } else {
            return;
        }
    } else {
        if (dataArea.contains(Math.min(xx0, xx1), Math.min(yy0, yy1), Math.abs(xx1 - xx0),
                Math.abs(yy0 - yy1))) {
            block = new Rectangle2D.Double(Math.min(xx0, xx1), Math.min(yy0, yy1), Math.abs(xx1 - xx0),
                    Math.abs(yy0 - yy1));
        } else {
            return;
        }
    }

    g2.setPaint(p);
    g2.fill(block);
    g2.setStroke(new BasicStroke(1.0f));
    g2.draw(block);
    EntityCollection entities = state.getEntityCollection();
    //        System.out.println("Entity collection is of type: "+entities.getClass());
    if (entities != null) {
        //System.out.println("Adding entity");
        addEntity(entities, block, dataset, series, item, block.getCenterX(), block.getCenterY());
    }

}

From source file:fr.fg.server.core.TerritoryManager.java

private static BufferedImage createTerritoryMap(int idSector) {
    List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector));

    float[][] points = new float[areas.size()][2];
    int[] dominatingAllies = new int[areas.size()];
    int i = 0;/*from   w  ww. j a  va  2s .co m*/
    for (Area area : areas) {
        points[i][0] = area.getX() * MAP_SCALE;
        points[i][1] = area.getY() * MAP_SCALE;
        dominatingAllies[i] = area.getIdDominatingAlly();
        i++;
    }

    Hull hull = new Hull(points);
    MPolygon hullPolygon = hull.getRegion();
    float[][] newPoints = new float[points.length + hullPolygon.count()][2];
    System.arraycopy(points, 0, newPoints, 0, points.length);

    float[][] hullCoords = hullPolygon.getCoords();

    for (i = 0; i < hullPolygon.count(); i++) {
        double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]);
        double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]);

        newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE));
        newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE));
    }

    points = newPoints;

    Voronoi voronoi = new Voronoi(points);
    Delaunay delaunay = new Delaunay(points);

    // Dcoupage en rgions
    MPolygon[] regions = voronoi.getRegions();

    // Calcule le rayon de la galaxie
    int radius = 0;

    for (Area area : areas) {
        radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY());
    }

    radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE;
    int diameter = 2 * radius + 1;

    // Construit l'image avec les quadrants
    BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = (Graphics2D) territoriesImage.getGraphics();

    // Affecte une couleur  chaque alliance
    HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>();

    for (Area area : areas) {
        int idDominatingAlly = area.getIdDominatingAlly();
        if (idDominatingAlly != 0)
            alliesColors.put(idDominatingAlly,
                    Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]);
    }

    Polygon[] polygons = new Polygon[regions.length];
    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] != 0) {
            polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3);
        }
    }

    // Dessine tous les secteurs
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        Polygon p = polygons[i];

        // Dessine le polygone
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.fill(p);

        // Rempli les espaces entre les polygones adjacents qui
        // correspondent au territoire d'une mme alliance
        int[] linkedRegions = delaunay.getLinked(i);
        for (int j = 0; j < linkedRegions.length; j++) {
            int linkedRegion = linkedRegions[j];

            if (linkedRegion >= areas.size())
                continue;

            if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                if (linkedRegion <= i)
                    continue;

                float[][] coords1 = regions[i].getCoords();
                float[][] coords2 = regions[linkedRegion].getCoords();

                int junctionIndex = 0;
                int[][] junctions = new int[2][2];

                search: for (int k = 0; k < coords1.length; k++) {
                    for (int l = 0; l < coords2.length; l++) {
                        if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) {
                            junctions[junctionIndex][0] = k;
                            junctions[junctionIndex][1] = l;

                            junctionIndex++;

                            if (junctionIndex == 2) {
                                int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]],
                                        polygons[linkedRegion].xpoints[junctions[0][1]],
                                        polygons[linkedRegion].xpoints[junctions[1][1]],
                                        polygons[i].xpoints[junctions[1][0]], };
                                int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]],
                                        polygons[linkedRegion].ypoints[junctions[0][1]],
                                        polygons[linkedRegion].ypoints[junctions[1][1]],
                                        polygons[i].ypoints[junctions[1][0]], };

                                Polygon border = new Polygon(xpts, ypts, 4);
                                g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
                                g.fill(border);
                                g.draw(border);
                                break search;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    // Dessine des lignes de contours des territoires
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        g.setStroke(new BasicStroke(1.5f));
        g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter());

        float[][] coords1 = regions[i].getCoords();

        lines: for (int j = 0; j < coords1.length; j++) {
            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]
                                && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1)
                                        % coords2.length][0]
                                        && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1)
                                                % coords2.length][1])
                                        || (coords1[(j + 1)
                                                % coords1.length][0] == coords2[(m - 1 + coords2.length)
                                                        % coords2.length][0]
                                                && coords1[(j + 1)
                                                        % coords1.length][1] == coords2[(m - 1 + coords2.length)
                                                                % coords2.length][1]))) {
                            continue lines;
                        }
                    }
                }
            }

            g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                    Math.round(polygons[i].xpoints[(j + 1) % coords1.length]),
                    Math.round(polygons[i].ypoints[(j + 1) % coords1.length]));
        }

        for (int j = 0; j < coords1.length; j++) {
            int neighbours = 0;
            int lastNeighbourRegion = -1;
            int neighbourCoordsIndex = -1;

            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) {
                            neighbours++;
                            lastNeighbourRegion = linkedRegion;
                            neighbourCoordsIndex = m;
                            break;
                        }
                    }
                }
            }

            if (neighbours == 1) {
                g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                        Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]),
                        Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex]));
            }
        }
    }

    BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    g = (Graphics2D) finalImage.getGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f));
    g.drawImage(territoriesImage, 0, 0, null);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f));

    // Charge la police pour afficher le nom des alliances
    try {
        Font textFont = Font.createFont(Font.TRUETYPE_FONT,
                Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf"));
        textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD);
        g.setFont(textFont);
    } catch (Exception e) {
        LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e);
    }
    FontMetrics fm = g.getFontMetrics();

    ArrayList<Integer> closedRegions = new ArrayList<Integer>();

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0 || closedRegions.contains(i))
            continue;

        ArrayList<Integer> allyRegions = new ArrayList<Integer>();
        ArrayList<Integer> openRegions = new ArrayList<Integer>();

        openRegions.add(i);

        while (openRegions.size() > 0) {
            int currentRegion = openRegions.remove(0);
            allyRegions.add(currentRegion);
            closedRegions.add(currentRegion);

            int[] linkedRegions = delaunay.getLinked(currentRegion);

            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion)
                        || allyRegions.contains(linkedRegion))
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion])
                    openRegions.add(linkedRegion);
            }
        }

        Area area = areas.get(i);
        long xsum = 0;
        long ysum = 0;

        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);
            area = areas.get(allyRegion);

            xsum += area.getX();
            ysum += area.getY();
        }

        int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1;
        int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1;
        ;

        Point point = new Point(x, y);
        boolean validLocation = false;
        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);

            if (polygons[allyRegion].contains(point)) {
                validLocation = true;
                break;
            }
        }

        if (validLocation) {
            if (allyRegions.size() == 1)
                y -= 14;
        } else {
            int xmid = (int) (xsum / allyRegions.size());
            int ymid = (int) (ysum / allyRegions.size());

            area = areas.get(i);
            int dx = area.getX() - xmid;
            int dy = area.getY() - ymid;
            int distance = dx * dx + dy * dy;

            int nearestAreaIndex = i;
            int nearestDistance = distance;

            for (int k = 0; k < allyRegions.size(); k++) {
                int allyRegion = allyRegions.get(k);

                area = areas.get(allyRegion);
                dx = area.getX() - xmid;
                dy = area.getY() - ymid;
                distance = dx * dx + dy * dy;

                if (distance < nearestDistance) {
                    nearestAreaIndex = allyRegion;
                    nearestDistance = distance;
                }
            }

            area = areas.get(nearestAreaIndex);
            x = area.getX() * MAP_SCALE + radius + 1;
            y = -area.getY() * MAP_SCALE + radius - 13;
        }

        // Dessine le tag de l'alliance
        String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]";
        g.setColor(Color.BLACK);
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y);
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y);
    }

    return finalImage;
}

From source file:org.photovault.swingui.PhotoCollectionThumbView.java

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    Rectangle clipRect = g.getClipBounds();
    Dimension compSize = getSize();
    // columnCount = (int)(compSize.getWidth()/columnWidth);

    int photoCount = 0;
    if (photos != null) {
        photoCount = photos.size();/*from  w w w.j  ava 2  s.c o m*/
    }

    // Determine the grid size based on couln & row count
    columnsToPaint = columnCount;
    // if columnCount is not specified determine it based on row count
    if (columnCount < 0) {
        if (rowCount > 0) {
            columnsToPaint = photoCount / rowCount;
            if (columnsToPaint * rowCount < photoCount) {
                columnsToPaint++;
            }
        } else {
            columnsToPaint = (int) (compSize.getWidth() / columnWidth);
        }
    }

    int col = 0;
    int row = 0;
    Rectangle thumbRect = new Rectangle();

    for (PhotoInfo photo : photos) {
        thumbRect.setBounds(col * columnWidth, row * rowHeight, columnWidth, rowHeight);
        if (thumbRect.intersects(clipRect)) {
            if (photo != null) {
                paintThumbnail(g2, photo, col * columnWidth, row * rowHeight, selection.contains(photo));
            }
        }
        col++;
        if (col >= columnsToPaint) {
            row++;
            col = 0;
        }
    }

    // Paint the selection rectangle if needed
    if (dragSelectionRect != null) {
        Stroke prevStroke = g2.getStroke();
        Color prevColor = g2.getColor();
        g2.setStroke(new BasicStroke(1.0f));
        g2.setColor(Color.BLACK);
        g2.draw(dragSelectionRect);
        g2.setColor(prevColor);
        g2.setStroke(prevStroke);
        lastDragSelectionRect = dragSelectionRect;
    }
}

From source file:com.bdb.weather.display.windplot.WindItemRenderer.java

/**
 * Draws the visual representation of a single data item.
 *
 * @param g2  the graphics device./* ww  w  . ja  v  a2 s .  c  o  m*/
 * @param rendererState  the renderer state.
 * @param dataArea  the area within which the data is being drawn.
 * @param info  collects information about the drawing.
 * @param plot  the plot (can be used to obtain standard color
 *              information etc).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset.
 * @param series  the series index (zero-based).
 * @param item  the item index (zero-based).
 * @param crosshairState  crosshair information for the plot
 *                        (<code>null</code> permitted).
 * @param pass  the pass index.
 */
@Override
public void drawItem(Graphics2D g2, XYItemRendererState rendererState, Rectangle2D dataArea,
        PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
        int series, int item, CrosshairState crosshairState, int pass) {
    //
    // Let the base class handle drawing the line and the shapes (passes 0 and 1). This class will handle drawing the
    // wind direction lines.
    //
    if (pass < 2)
        super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item,
                crosshairState, pass);
    else {
        if (!(dataset instanceof TimeSeriesCollection) || !showWindDirectionLines)
            return;

        if (item == 0)
            state.resetLastDirection();

        RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
        RectangleEdge yAxisLocation = plot.getRangeAxisEdge();

        TimeSeriesCollection collection = (TimeSeriesCollection) dataset;
        TimeSeries timeSeries = collection.getSeries(series);

        if (!(timeSeries instanceof WindSeries))
            return;

        WindSeries windSeries = (WindSeries) timeSeries;
        WindSeriesDataItem windItem = windSeries.getWindDataItem(item);
        double speed = windItem.getWindSpeed().doubleValue();
        double time = dataset.getXValue(series, item);
        double dir = windItem.getWindDirection().doubleValue();

        if (speed > 0.0 && dir != state.getLastDirection()) {
            state.setLastDirection(dir);
            double radians = Math.toRadians(dir - 90.0);
            double dirXOffset = directionLineLength * Math.cos(radians);
            double dirYOffset = directionLineLength * Math.sin(radians);

            double transTime = domainAxis.valueToJava2D(time, dataArea, xAxisLocation);
            double transSpeed = rangeAxis.valueToJava2D(speed, dataArea, yAxisLocation);
            double dirX = transTime + dirXOffset;
            double dirY = transSpeed + dirYOffset;

            // update path to reflect latest point
            if (!Double.isNaN(transTime) && !Double.isNaN(transSpeed)) {
                int x1 = (int) transTime;
                int y1 = (int) transSpeed;
                int x2 = (int) dirX;
                int y2 = (int) dirY;
                PlotOrientation orientation = plot.getOrientation();
                if (orientation == PlotOrientation.HORIZONTAL) {
                    x1 = (int) transSpeed;
                    y1 = (int) transTime;
                    x2 = (int) dirY;
                    y2 = (int) dirX;
                }
                g2.setPaint(windDirectionPaint);
                g2.setStroke(windDirectionStroke);
                g2.drawLine(x1, y1, x2, y2);
            }
        }
    }
}