Example usage for java.awt Graphics2D draw

List of usage examples for java.awt Graphics2D draw

Introduction

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

Prototype

public abstract void draw(Shape s);

Source Link

Document

Strokes the outline of a Shape using the settings of the current Graphics2D context.

Usage

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

protected void paintComponent(Graphics g) {

    // prepare graphic object
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // set clipping area
    if (is_printing) {
        g2d.translate(-draw_area.x, -draw_area.y);
        g2d.setClip(draw_area);//from   w w w . j a  va  2  s .c om
    }

    //paint canvas background
    if (!is_printing) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
    }

    // paint white background on drawing area    
    g2d.setColor(Color.white);
    g2d.fillRect(draw_area.x, draw_area.y, draw_area.width, draw_area.height);
    if (!is_printing) {
        g2d.setColor(Color.black);
        g2d.draw(draw_area);
    }

    // paint
    paintChart(g2d);
    paintAnnotations(g2d);

    // dispose graphic object
    g2d.dispose();

    if (!is_printing) {
        if (first_time) {
            if (first_time_init_pos)
                placeStructures(true);
            else
                theDocument.fireDocumentInit();
            first_time = false;
        } else
            revalidate();
    }

}

From source file:org.squidy.designer.zoom.ConnectorShape.java

@Override
protected void paintShapeZoomedIn(PPaintContext paintContext) {
    super.paintShapeZoomedIn(paintContext);

    if (getInputPort().getVisible() || getOutputPort().getVisible()) {
        Graphics2D g = paintContext.getGraphics();
        PBounds bounds = getBoundsReference();
        double x = bounds.getX();
        double y = bounds.getY();
        double centerY = bounds.getCenterY();
        double width = bounds.getWidth();

        // Paint a border for zoom ports.
        // g.setStroke(new BasicStroke(6f));

        // g.setColor(Color.RED);
        // g.draw(getBoundsReference());

        // Painting left port.
        if (getInputPort().getVisible()) {

            if (shapePortLeft == null) {
                double portScale = inputPort.getScale();
                double portWidth = inputPort.getWidth() * portScale;
                double portHeight = inputPort.getHeight() * portScale;

                shapePortLeft = new RoundRectangle2D.Double(x - portWidth + 15, centerY - portHeight / 2 - 5,
                        35, 60, 10, 10);
            }/*from  ww w  .  j  a  v  a2  s. com*/

            Rectangle boundsPort = shapePortLeft.getBounds();
            g.setColor(Constants.Color.COLOR_SHAPE_BACKGROUND);
            if (isRenderPrimitiveRect())
                g.fillRect(boundsPort.x, boundsPort.y, boundsPort.width, boundsPort.height);
            else
                g.fill(shapePortLeft);

            g.setColor(Constants.Color.COLOR_SHAPE_BORDER);
            g.setStroke(StrokeUtils.getBasicStroke(3f));
            if (isRenderPrimitiveRect())
                g.drawRect(boundsPort.x, boundsPort.y, boundsPort.width, boundsPort.height);
            else
                g.draw(shapePortLeft);
        }

        // Painting right port.
        if (getOutputPort().getVisible()) {

            if (shapePortRight == null) {
                double portScale = outputPort.getScale();
                double portWidth = outputPort.getWidth() * portScale;
                double portHeight = outputPort.getHeight() * portScale;

                shapePortRight = new RoundRectangle2D.Double(x + width - portWidth - 21,
                        centerY - portHeight / 2 - 5, 35, 60, 10, 10);
            }

            Rectangle boundsPort = shapePortRight.getBounds();
            g.setColor(Constants.Color.COLOR_SHAPE_BACKGROUND);
            if (isRenderPrimitiveRect())
                g.fillRect(boundsPort.x, boundsPort.y, boundsPort.width, boundsPort.height);
            else
                g.fill(shapePortRight);

            g.setColor(Constants.Color.COLOR_SHAPE_BORDER);
            g.setStroke(StrokeUtils.getBasicStroke(3f));
            if (isRenderPrimitiveRect())
                g.drawRect(boundsPort.x, boundsPort.y, boundsPort.width, boundsPort.height);
            else
                g.draw(shapePortRight);
        }
    }
}

From source file:edu.cuny.jfree.chart.renderer.category.ValueListShapeRenderer.java

@Override
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, final int pass) {

    final ListCategoryDataset setData = (ListCategoryDataset) dataset;

    final List list = setData.getList(row, column);
    if (list == null) {
        return;/*from w w  w .  j  a  va 2 s.c om*/
    }

    final PlotOrientation orientation = plot.getOrientation();
    final double x = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge());

    final Iterator iterator = list.iterator();
    while (iterator.hasNext()) {
        final Number value = (Number) iterator.next();
        final double y = rangeAxis.valueToJava2D(value.doubleValue(), dataArea, plot.getRangeAxisEdge());

        Shape shape = getItemShape(row, column);

        if (orientation == PlotOrientation.HORIZONTAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, y, x);
        } else if (orientation == PlotOrientation.VERTICAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, x, y);
        }
        if (getItemShapeVisible(row, column)) {
            if (getItemShapeFilled(row, column)) {
                g2.setPaint(getItemPaint(row, column));
                g2.fill(shape);
            } else {
                if (getUseOutlinePaint()) {
                    g2.setPaint(getItemOutlinePaint(row, column));
                } else {
                    g2.setPaint(getItemPaint(row, column));
                }
                g2.setStroke(getItemOutlineStroke(row, column));
                g2.draw(shape);
            }
        }
        g2.setPaint(getItemPaint(row, column));

        if (isItemLabelVisible(row, column)) {
            if (orientation == PlotOrientation.HORIZONTAL) {
                drawItemLabel(g2, orientation, dataset, row, column, y, x, value.doubleValue() < 0.0D);
            } else if (orientation == PlotOrientation.VERTICAL) {
                drawItemLabel(g2, orientation, dataset, row, column, x, y, value.doubleValue() < 0.0D);
            }
        }

        if (state.getInfo() != null) {
            final EntityCollection entities = state.getEntityCollection();
            if ((entities != null) && (shape != 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(shape, tip, url, dataset,
                        dataset.getRowKey(row), dataset.getColumnKey(column));
                entities.add(entity);
            }
        }
    }
}

From source file:au.org.ala.biocache.web.MapController.java

@Deprecated
@RequestMapping(value = "/occurrences/wms", method = RequestMethod.GET)
public void pointsWmsImage(SpatialSearchRequestParams requestParams,
        @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby,
        @RequestParam(value = "width", required = false, defaultValue = "256") Integer widthObj,
        @RequestParam(value = "height", required = false, defaultValue = "256") Integer heightObj,
        @RequestParam(value = "zoom", required = false, defaultValue = "0") Integer zoomLevel,
        @RequestParam(value = "symsize", required = false, defaultValue = "4") Integer symsize,
        @RequestParam(value = "symbol", required = false, defaultValue = "circle") String symbol,
        @RequestParam(value = "bbox", required = false, defaultValue = "110,-45,157,-9") String bboxString,
        @RequestParam(value = "type", required = false, defaultValue = "normal") String type,
        @RequestParam(value = "outline", required = true, defaultValue = "false") boolean outlinePoints,
        @RequestParam(value = "outlineColour", required = true, defaultValue = "0x000000") String outlineColour,
        HttpServletResponse response) throws Exception {

    // size of the circles
    int size = symsize.intValue();
    int width = widthObj.intValue();
    int height = heightObj.intValue();

    requestParams.setStart(0);/*from w ww  .  j ava2  s . c om*/
    requestParams.setPageSize(Integer.MAX_VALUE);
    String query = requestParams.getQ();
    String[] filterQuery = requestParams.getFq();

    if (StringUtils.isBlank(query) && StringUtils.isBlank(requestParams.getFormattedQuery())) {
        displayBlankImage(width, height, false, response);
        return;
    }

    // let's force it to PNG's for now 
    response.setContentType("image/png");

    // Convert array to list so we append more values onto it
    ArrayList<String> fqList = null;
    if (filterQuery != null) {
        fqList = new ArrayList<String>(Arrays.asList(filterQuery));
    } else {
        fqList = new ArrayList<String>();
    }

    // the bounding box
    double[] bbox = new double[4];
    int i;
    i = 0;
    for (String s : bboxString.split(",")) {
        try {
            bbox[i] = Double.parseDouble(s);
            i++;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    double pixelWidth = (bbox[2] - bbox[0]) / width;
    double pixelHeight = (bbox[3] - bbox[1]) / height;
    bbox[0] += pixelWidth / 2;
    bbox[2] -= pixelWidth / 2;
    bbox[1] += pixelHeight / 2;
    bbox[3] -= pixelHeight / 2;

    //offset for points bounding box by size
    double xoffset = (bbox[2] - bbox[0]) / (double) width * (size * 2);
    double yoffset = (bbox[3] - bbox[1]) / (double) height * (size * 2);

    //adjust offset for pixel height/width
    xoffset += pixelWidth;
    yoffset += pixelHeight;

    double[] bbox2 = new double[4];
    bbox2[0] = convertMetersToLng(bbox[0] - xoffset);
    bbox2[1] = convertMetersToLat(bbox[1] - yoffset);
    bbox2[2] = convertMetersToLng(bbox[2] + xoffset);
    bbox2[3] = convertMetersToLat(bbox[3] + yoffset);

    bbox[0] = convertMetersToLng(bbox[0]);
    bbox[1] = convertMetersToLat(bbox[1]);
    bbox[2] = convertMetersToLng(bbox[2]);
    bbox[3] = convertMetersToLat(bbox[3]);

    double[] pbbox = new double[4]; //pixel bounding box
    pbbox[0] = convertLngToPixel(bbox[0]);
    pbbox[1] = convertLatToPixel(bbox[1]);
    pbbox[2] = convertLngToPixel(bbox[2]);
    pbbox[3] = convertLatToPixel(bbox[3]);

    String bboxString2 = bbox2[0] + "," + bbox2[1] + "," + bbox2[2] + "," + bbox2[3];
    bboxToQuery(bboxString2, fqList);

    PointType pointType = getPointTypeForZoomLevel(zoomLevel);

    String[] newFilterQuery = (String[]) fqList.toArray(new String[fqList.size()]); // convert back to array

    requestParams.setFq(newFilterQuery);

    List<OccurrencePoint> points = searchDAO.getFacetPoints(requestParams, pointType);
    logger.debug("Points search for " + pointType.getLabel() + " - found: " + points.size());

    if (points.size() == 0) {
        displayBlankImage(width, height, false, response);
        return;
    }

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setColor(Color.RED);

    int x, y;
    int pointWidth = size * 2;
    double width_mult = (width / (pbbox[2] - pbbox[0]));
    double height_mult = (height / (pbbox[1] - pbbox[3]));

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

    Color oColour = Color.decode(outlineColour);

    for (i = 0; i < points.size(); i++) {
        OccurrencePoint pt = points.get(i);
        float lng = pt.getCoordinates().get(0).floatValue();
        float lat = pt.getCoordinates().get(1).floatValue();

        x = (int) ((convertLngToPixel(lng) - pbbox[0]) * width_mult);
        y = (int) ((convertLatToPixel(lat) - pbbox[3]) * height_mult);

        if (colourby != null) {
            int colour = 0xFF000000 | colourby.intValue();
            Color c = new Color(colour);
            g.setPaint(c);
        } else {
            g.setPaint(Color.blue);
        }

        // g.fillOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        Shape shp = getShape(symbol, x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        g.draw(shp);
        g.fill(shp);
        if (outlinePoints) {
            g.setPaint(oColour);
            g.drawOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        }
    }

    g.dispose();

    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:org.tsho.dmc2.core.chart.jfree.DmcChartPanel.java

/**
 * Handles a 'mouse dragged' event./*w w w  .ja  v  a  2 s.co m*/
 *
 * @param e  the mouse event.
 */
public void mouseDragged(MouseEvent e) {

    if (this.zoomingEnabled) {
        // if the popup menu has already been triggered, then ignore dragging...
        if (popup != null && popup.isShowing()) {
            return;
        }

        Graphics2D g2 = (Graphics2D) getGraphics();

        // use XOR to erase the previous zoom rectangle (if any)...
        g2.setXORMode(java.awt.Color.gray);
        if (zoomRectangle != null) {
            if (fillZoomRectangle) {
                g2.fill(zoomRectangle);
            } else {
                g2.draw(zoomRectangle);
            }
        }

        Rectangle2D scaledDataArea = getScaledDataArea();
        if (this.horizontalZoom && this.verticalZoom) {
            // selected rectangle shouldn't extend outside the data area...
            double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
            double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
            zoomRectangle = new Rectangle2D.Double(zoomPoint.getX(), zoomPoint.getY(), xmax - zoomPoint.getX(),
                    ymax - zoomPoint.getY());
        } else if (this.horizontalZoom) {
            double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
            zoomRectangle = new Rectangle2D.Double(zoomPoint.getX(), scaledDataArea.getMinY(),
                    xmax - zoomPoint.getX(), scaledDataArea.getHeight());
        } else if (this.verticalZoom) {
            double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
            zoomRectangle = new Rectangle2D.Double(scaledDataArea.getMinX(), zoomPoint.getY(),
                    scaledDataArea.getWidth(), ymax - zoomPoint.getY());
        }

        if (zoomRectangle != null) {
            // use XOR to draw the new zoom rectangle...
            if (fillZoomRectangle) {
                g2.fill(zoomRectangle);
            } else {
                g2.draw(zoomRectangle);
            }
        }
        g2.dispose();
    }
}

From source file:ClipImage.java

public void drawDemo(Graphics2D g2) {

    if (newBufferedImage) {
        x = Math.random() * w;/*from  ww  w . j  ava2  s. c  o m*/
        y = Math.random() * h;
        ew = (Math.random() * w) / 2;
        eh = (Math.random() * h) / 2;
    }
    x += ix;
    y += iy;
    ew += iw;
    eh += ih;
    if (ew > w / 2) {
        ew = w / 2;
        iw = Math.random() * -w / 16 - 1;
    }
    if (ew < w / 8) {
        ew = w / 8;
        iw = Math.random() * w / 16 + 1;
    }
    if (eh > h / 2) {
        eh = h / 2;
        ih = Math.random() * -h / 16 - 1;
    }
    if (eh < h / 8) {
        eh = h / 8;
        ih = Math.random() * h / 16 + 1;
    }
    if ((x + ew) > w) {
        x = (w - ew) - 1;
        ix = Math.random() * -w / 32 - 1;
    }
    if (x < 0) {
        x = 2;
        ix = Math.random() * w / 32 + 1;
    }
    if ((y + eh) > h) {
        y = (h - eh) - 2;
        iy = Math.random() * -h / 32 - 1;
    }
    if (y < 0) {
        y = 2;
        iy = Math.random() * h / 32 + 1;
    }

    ellipse.setFrame(x, y, ew, eh);
    g2.setClip(ellipse);

    rect.setRect(x + 5, y + 5, ew - 10, eh - 10);
    g2.clip(rect);

    g2.drawImage(img, 0, 0, w, h, this);

    p.reset();
    p.moveTo(-w / 2.0f, -h / 8.0f);
    p.lineTo(+w / 2.0f, -h / 8.0f);
    p.lineTo(-w / 4.0f, +h / 2.0f);
    p.lineTo(+0.0f, -h / 2.0f);
    p.lineTo(+w / 4.0f, +h / 2.0f);
    p.closePath();

    at.setToIdentity();
    at.translate(w * .5f, h * .5f);
    g2.transform(at);
    g2.setStroke(bs);
    g2.setPaint(redBlend);
    g2.draw(p);

    at.setToIdentity();
    g2.setTransform(at);

    g2.setPaint(greenBlend);

    for (int yy = 0; yy < h; yy += 50) {
        for (int xx = 0, i = 0; xx < w; i++, xx += 50) {
            switch (i) {
            case 0:
                arc.setArc(xx, yy, 25, 25, 45, 270, Arc2D.PIE);
                g2.fill(arc);
                break;
            case 1:
                ellipse.setFrame(xx, yy, 25, 25);
                g2.fill(ellipse);
                break;
            case 2:
                roundRect.setRoundRect(xx, yy, 25, 25, 4, 4);
                g2.fill(roundRect);
                break;
            case 3:
                rect.setRect(xx, yy, 25, 25);
                g2.fill(rect);
                i = -1;
            }

        }
    }
}

From source file:ClipImage.java

public void drawDemo(Graphics2D g2) {
    if (newBufferedImage) {
        x = Math.random() * w;/*w  w w.j  a va 2 s . c o  m*/
        y = Math.random() * h;
        ew = (Math.random() * w) / 2;
        eh = (Math.random() * h) / 2;
    }
    x += ix;
    y += iy;
    ew += iw;
    eh += ih;
    if (ew > w / 2) {
        ew = w / 2;
        iw = Math.random() * -w / 16 - 1;
    }
    if (ew < w / 8) {
        ew = w / 8;
        iw = Math.random() * w / 16 + 1;
    }
    if (eh > h / 2) {
        eh = h / 2;
        ih = Math.random() * -h / 16 - 1;
    }
    if (eh < h / 8) {
        eh = h / 8;
        ih = Math.random() * h / 16 + 1;
    }
    if ((x + ew) > w) {
        x = (w - ew) - 1;
        ix = Math.random() * -w / 32 - 1;
    }
    if (x < 0) {
        x = 2;
        ix = Math.random() * w / 32 + 1;
    }
    if ((y + eh) > h) {
        y = (h - eh) - 2;
        iy = Math.random() * -h / 32 - 1;
    }
    if (y < 0) {
        y = 2;
        iy = Math.random() * h / 32 + 1;
    }

    ellipse.setFrame(x, y, ew, eh);
    g2.setClip(ellipse);

    rect.setRect(x + 5, y + 5, ew - 10, eh - 10);
    g2.clip(rect);

    g2.drawImage(img, 0, 0, w, h, this);

    p.reset();
    p.moveTo(-w / 2.0f, -h / 8.0f);
    p.lineTo(+w / 2.0f, -h / 8.0f);
    p.lineTo(-w / 4.0f, +h / 2.0f);
    p.lineTo(+0.0f, -h / 2.0f);
    p.lineTo(+w / 4.0f, +h / 2.0f);
    p.closePath();

    at.setToIdentity();
    at.translate(w * .5f, h * .5f);
    g2.transform(at);
    g2.setStroke(bs);
    g2.setPaint(redBlend);
    g2.draw(p);

    at.setToIdentity();
    g2.setTransform(at);

    g2.setPaint(greenBlend);

    for (int yy = 0; yy < h; yy += 50) {
        for (int xx = 0, i = 0; xx < w; i++, xx += 50) {
            switch (i) {
            case 0:
                arc.setArc(xx, yy, 25, 25, 45, 270, Arc2D.PIE);
                g2.fill(arc);
                break;
            case 1:
                ellipse.setFrame(xx, yy, 25, 25);
                g2.fill(ellipse);
                break;
            case 2:
                roundRect.setRoundRect(xx, yy, 25, 25, 4, 4);
                g2.fill(roundRect);
                break;
            case 3:
                rect.setRect(xx, yy, 25, 25);
                g2.fill(rect);
                i = -1;
            }

        }
    }
}

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

/**
 * Draws the block representing the specified item.
 * /*from  w w  w. j  av a  2s.  c o  m*/
 * @param g2
 *            the graphics device.
 * @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) {

    Shape hotspot = null;
    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }

    double x = dataset.getXValue(series, item);
    double y = dataset.getYValue(series, item);
    double colorValue = ((XYZDataset) dataset).getZValue(series, item);
    double normalized = (colorValue - minColor) / (maxColor - minColor);

    if (Double.isNaN(x) || Double.isNaN(y)) {
        // can't draw anything
        return;
    }

    double transX = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge());
    double transY = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge());

    PlotOrientation orientation = plot.getOrientation();

    Shape shape = getItemShape(series, item);
    if (orientation == PlotOrientation.HORIZONTAL) {
        shape = ShapeUtilities.createTranslatedShape(shape, transY, transX);
    } else if (orientation == PlotOrientation.VERTICAL) {
        shape = ShapeUtilities.createTranslatedShape(shape, transX, transY);
    }
    hotspot = shape;
    if (shape.intersects(dataArea)) {
        g2.setPaint(colorProvider.getPointColor(normalized));
        g2.fill(shape);
        if (getDrawOutlines()) {
            if (getUseOutlinePaint()) {
                g2.setPaint(getItemOutlinePaint(series, item));
            } else {
                g2.setPaint(getItemPaint(series, item));
            }
            g2.setStroke(getItemOutlineStroke(series, item));
            g2.draw(shape);
        }
    }

    // add an entity for the item...
    if (entities != null) {
        addEntity(entities, hotspot, dataset, series, item, transX, transY);
    }
}

From source file:ColorBlocks.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    Dimension d = getSize();/*from w w w.j  a  v  a  2  s  . c  om*/
    g2.translate(d.width / 2, d.height / 2);

    Color[] colors = { Color.white, Color.lightGray, Color.gray, Color.darkGray, Color.black, Color.red,
            Color.pink, Color.orange, Color.yellow, Color.green, Color.magenta, Color.cyan, Color.blue };

    float size = 25;
    float x = -size * colors.length / 2;
    float y = -size * 3 / 2;

    // Show all the predefined colors.
    for (int i = 0; i < colors.length; i++) {
        Rectangle2D r = new Rectangle2D.Float(x + size * (float) i, y, size, size);
        g2.setPaint(colors[i]);
        g2.fill(r);
    }

    //a linear gradient.
    y += size;
    Color c1 = Color.yellow;
    Color c2 = Color.blue;
    for (int i = 0; i < colors.length; i++) {
        float ratio = (float) i / (float) colors.length;
        int red = (int) (c2.getRed() * ratio + c1.getRed() * (1 - ratio));
        int green = (int) (c2.getGreen() * ratio + c1.getGreen() * (1 - ratio));
        int blue = (int) (c2.getBlue() * ratio + c1.getBlue() * (1 - ratio));
        Color c = new Color(red, green, blue);
        Rectangle2D r = new Rectangle2D.Float(x + size * (float) i, y, size, size);
        g2.setPaint(c);
        g2.fill(r);
    }

    // Show an alpha gradient.
    y += size;
    c1 = Color.red;
    for (int i = 0; i < colors.length; i++) {
        int alpha = (int) (255 * (float) i / (float) colors.length);
        Color c = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), alpha);
        Rectangle2D r = new Rectangle2D.Float(x + size * (float) i, y, size, size);
        g2.setPaint(c);
        g2.fill(r);
    }

    // Draw a frame around the whole thing.
    y -= size * 2;
    Rectangle2D frame = new Rectangle2D.Float(x, y, size * colors.length, size * 3);
    g2.setPaint(Color.black);
    g2.draw(frame);
}

From source file:com.att.aro.ui.view.diagnostictab.CreateBarPlot.java

public XYPlot drawYIntervalPlot() {
    // Create the plot renderer
    YIntervalRenderer renderer = new YIntervalRenderer() {
        private static final long serialVersionUID = 1L;

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

            // setup for collecting optional entity info...
            Shape entityArea = null;
            EntityCollection entities = null;
            if (info != null) {
                entities = info.getOwner().getEntityCollection();
            }/*  www.ja  v  a2  s  . c  om*/

            IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset;

            double x = intervalDataset.getXValue(series, item);
            double yLow = intervalDataset.getStartYValue(series, item);
            double yHigh = intervalDataset.getEndYValue(series, item);

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

            double xx = domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
            double yyLow = rangeAxis.valueToJava2D(yLow, dataArea, yAxisLocation);
            double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea, yAxisLocation);

            Paint p = getItemPaint(series, item);
            Stroke s = getItemStroke(series, item);

            Line2D line = null;
            PlotOrientation orientation = plot.getOrientation();
            if (orientation == PlotOrientation.HORIZONTAL) {
                line = new Line2D.Double(yyLow, xx, yyHigh, xx);
            } else if (orientation == PlotOrientation.VERTICAL) {
                line = new Line2D.Double(xx, yyLow, xx, yyHigh);
            }
            g2.setPaint(p);
            g2.setStroke(s);
            g2.draw(line);

            // add an entity for the item...
            if (entities != null && line != null) {
                if (entityArea == null) {
                    entityArea = line.getBounds();
                }
                String tip = null;
                XYToolTipGenerator generator = getToolTipGenerator(series, item);
                if (generator != null) {
                    tip = generator.generateToolTip(dataset, series, item);
                }
                XYItemEntity entity = new XYItemEntity(entityArea, dataset, series, item, tip, null);
                entities.add(entity);
            }

        }

    };
    renderer.setAdditionalItemLabelGenerator(null);
    renderer.setBaseShape(new Rectangle());
    renderer.setAutoPopulateSeriesShape(false);
    renderer.setAutoPopulateSeriesPaint(false);
    renderer.setBasePaint(Color.GRAY);

    // Create the plot
    XYPlot plot = new XYPlot(null, null, new NumberAxis(), renderer);
    plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
    plot.getRangeAxis().setVisible(false);

    return plot;
}