Example usage for java.awt Graphics2D setPaint

List of usage examples for java.awt Graphics2D setPaint

Introduction

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

Prototype

public abstract void setPaint(Paint paint);

Source Link

Document

Sets the Paint attribute for the Graphics2D context.

Usage

From source file:ImageDuplicity.java

private void createOffscreenImage() {
    Dimension d = getSize();/*from  ww w.j av a2s.c  o  m*/
    int width = d.width;
    int height = d.height;
    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = image.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    try {
        String filename = "largeJava2sLogo.jpg";
        InputStream in = getClass().getResourceAsStream(filename);
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
        BufferedImage image = decoder.decodeAsBufferedImage();
        in.close();
        g2.drawImage(image, 0, 0, width, height, null);
    } catch (Exception e) {
        System.out.print(e);
    }

    g2.setStroke(new BasicStroke(2));
    Color[] colors = { Color.red, Color.blue, Color.green };
    for (int i = -32; i < 40; i += 8) {
        g2.setPaint(colors[Math.abs(i) % 3]);
        g2.drawOval(i, i, width - i * 2, height - i * 2);
    }
}

From source file:RadialGradientApp.java

@Override
protected void paintComponent(Graphics g) {
    setFont(getFont().deriveFont(70.f).deriveFont(Font.BOLD));

    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // Retains the previous state
    Paint oldPaint = g2.getPaint();

    // Fills the circle with solid blue color
    g2.setColor(new Color(0x0153CC));
    g2.fillOval(0, 0, getWidth() - 1, getHeight() - 1);

    // Adds shadows at the top
    Paint p;/*ww  w  .  ja v  a 2 s .c  o  m*/
    p = new GradientPaint(0, 0, new Color(0.0f, 0.0f, 0.0f, 0.4f), 0, getHeight(),
            new Color(0.0f, 0.0f, 0.0f, 0.0f));
    g2.setPaint(p);
    g2.fillOval(0, 0, getWidth() - 1, getHeight() - 1);

    // Adds highlights at the bottom 
    p = new GradientPaint(0, 0, new Color(1.0f, 1.0f, 1.0f, 0.0f), 0, getHeight(),
            new Color(1.0f, 1.0f, 1.0f, 0.4f));
    g2.setPaint(p);
    g2.fillOval(0, 0, getWidth() - 1, getHeight() - 1);

    // Creates dark edges for 3D effect
    p = new RadialGradientPaint(new Point2D.Double(getWidth() / 2.0, getHeight() / 2.0), getWidth() / 2.0f,
            new float[] { 0.0f, 1.0f },
            new Color[] { new Color(6, 76, 160, 127), new Color(0.0f, 0.0f, 0.0f, 0.8f) });
    g2.setPaint(p);
    g2.fillOval(0, 0, getWidth() - 1, getHeight() - 1);

    // Adds oval inner highlight at the bottom
    p = new RadialGradientPaint(new Point2D.Double(getWidth() / 2.0, getHeight() * 1.5), getWidth() / 2.3f,
            new Point2D.Double(getWidth() / 2.0, getHeight() * 1.75 + 6), new float[] { 0.0f, 0.8f },
            new Color[] { new Color(64, 142, 203, 255), new Color(64, 142, 203, 0) },
            RadialGradientPaint.CycleMethod.NO_CYCLE, RadialGradientPaint.ColorSpaceType.SRGB,
            AffineTransform.getScaleInstance(1.0, 0.5));
    g2.setPaint(p);
    g2.fillOval(0, 0, getWidth() - 1, getHeight() - 1);

    // Adds oval specular highlight at the top left
    p = new RadialGradientPaint(new Point2D.Double(getWidth() / 2.0, getHeight() / 2.0), getWidth() / 1.4f,
            new Point2D.Double(45.0, 25.0), new float[] { 0.0f, 0.5f },
            new Color[] { new Color(1.0f, 1.0f, 1.0f, 0.4f), new Color(1.0f, 1.0f, 1.0f, 0.0f) },
            RadialGradientPaint.CycleMethod.NO_CYCLE);
    g2.setPaint(p);
    g2.fillOval(0, 0, getWidth() - 1, getHeight() - 1);

    // Restores the previous state
    g2.setPaint(oldPaint);

    // Draws the logo        
    //        FontRenderContext context = g2.getFontRenderContext();
    //        TextLayout layout = new TextLayout("R", getFont(), context);
    //        Rectangle2D bounds = layout.getBounds();
    //        
    //        float x = (getWidth() - (float) bounds.getWidth()) / 2.0f;
    //        float y = (getHeight() + (float) bounds.getHeight()) / 2.0f;
    //        
    //        g2.setColor(Color.WHITE);
    //        layout.draw(g2, x, y);
    //        
    //        Area shadow = new Area(layout.getOutline(null));
    //        shadow.subtract(new Area(layout.getOutline(AffineTransform.getTranslateInstance(1.0, 1.0))));
    //        g2.setColor(Color.BLACK);
    //        g2.translate(x, y);
    //        g2.fill(shadow);
    //        g2.translate(-x, -y);
}

From source file:org.jfree.experimental.chart.plot.dial.StandardDialFrame.java

/**
 * Draws the frame.//w  w  w  .jav  a 2s  . c  o  m
 * 
 * @param g2  the graphics target.
 * @param plot  the plot.
 * @param frame  the dial's reference frame.
 * @param view  the dial's view rectangle.
 */
public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) {

    Shape window = getWindow(frame);
    Shape outerWindow = getOuterWindow(frame);

    Area area1 = new Area(outerWindow);
    Area area2 = new Area(window);
    area1.subtract(area2);
    g2.setPaint(Color.lightGray);
    g2.fill(area1);

    g2.setStroke(this.stroke);
    g2.setPaint(this.foregroundPaint);
    g2.draw(window);
    g2.draw(outerWindow);

}

From source file:org.openfaces.component.chart.impl.renderers.XYLineFillRenderer.java

private void drawItemShape(Graphics2D g2, int series, int item, Shape entityShape) {
    if (getItemShapeFilled(series, item)) {
        g2.setPaint(getUseFillPaint() ? getItemFillPaint(series, item) : getItemPaint(series, item));
        g2.fill(entityShape);//  w  w  w . ja  v a2  s. c  o  m
    }

    if (getDrawOutlines()) {
        g2.setPaint(getUseOutlinePaint() ? getItemOutlinePaint(series, item) : getItemPaint(series, item));
        g2.setStroke(getItemOutlineStroke(series, item));
    }

    g2.draw(entityShape);
}

From source file:FontTest.java

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

    String message = "Hello, World!";

    Font f = new Font("Serif", Font.BOLD, 36);
    g2.setFont(f);//from  ww w.ja v  a2 s. c  om

    // measure the size of the message

    FontRenderContext context = g2.getFontRenderContext();
    Rectangle2D bounds = f.getStringBounds(message, context);

    // set (x,y) = top left corner of text

    double x = (getWidth() - bounds.getWidth()) / 2;
    double y = (getHeight() - bounds.getHeight()) / 2;

    // add ascent to y to reach the baseline

    double ascent = -bounds.getY();
    double baseY = y + ascent;

    // draw the message

    g2.drawString(message, (int) x, (int) baseY);

    g2.setPaint(Color.LIGHT_GRAY);

    // draw the baseline

    g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));

    // draw the enclosing rectangle

    Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight());
    g2.draw(rect);
}

From source file:org.jfree.demo.DrawStringPanel.java

/**
 * Paints the panel.//from  w  w w .  j  av a2 s  .c  o  m
 *
 * @param g  the graphics device.
 */
public void paintComponent(final Graphics g) {

    super.paintComponent(g);
    final Graphics2D g2 = (Graphics2D) g;

    final Dimension size = getSize();
    final Insets insets = getInsets();
    final Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
            size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom);

    final double x = available.getCenterX();
    final double y = available.getCenterY();

    final Line2D line1 = new Line2D.Double(x - 2.0, y + 2.0, x + 2.0, y - 2.0);
    final Line2D line2 = new Line2D.Double(x - 2.0, y - 2.0, x + 2.0, y + 2.0);
    g2.setPaint(Color.red);
    g2.draw(line1);
    g2.draw(line2);

    g2.setFont(this.font);
    g2.setPaint(Color.black);
    if (this.rotate) {
        TextUtilities.drawRotatedString(this.text, g2, (float) x, (float) y, this.anchor, this.angle,
                this.rotationAnchor);
    } else {
        TextUtilities.drawAlignedString(this.text, g2, (float) x, (float) y, this.anchor);
    }

}

From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("entered do Post for /resource");
    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && !IConstants.CT_RDF_XML.equals(contentType)) {
        throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }/*from   w  w  w. j  a va 2 s  . c  o m*/

    InputStream content = request.getInputStream();

    if (isFileUpload) {
        // being uploaded from a web page
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            // find the first (and only) file resource in the post
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // this is a form field, maybe we can accept a title or descr?
                } else {
                    content = item.getInputStream();
                    contentType = item.getContentType();
                }
            }

        } catch (Exception e) {
            throw new ShareServiceException(e);
        }
    }

    ShareStore store = this.getStore();
    if (ShareStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(resUri);
            List<ShareStatement> statements = store.parse(resUri, content, contentType);
            resource.addStatements(statements);
            String userUri = getUserUri(request.getRemoteUser());

            // if it parsed, then add it to the store.
            store.update(resource, userUri);

            // now get it back, to find 
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    } else if (IAmConstants.CT_APP_X_VND_MSPPT.equals(contentType) || isFileUpload) {
        try {

            ByteArrayInputStream bais = isToBais(content);

            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(uri);
            resource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
            resource.addRdfType(IAmConstants.RIO_AM_PPT_DECK);
            String id = resource.getIdentifier();
            String deckTitle = "PPT Deck " + id;
            resource.setTitle(deckTitle);
            resource.setDescription("A Power Point Deck");
            String sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());

            store.storeBinaryResource(bais, id);
            bais.reset();

            SlideShow ppt = new SlideShow(bais);
            Dimension pgsize = ppt.getPageSize();

            Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                String slideTitle = extractTitle(slide[i]);
                String slideUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
                SharepointResource slideResource = new SharepointResource(slideUri);
                slideResource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
                slideResource.addRdfType(IAmConstants.RIO_AM_PPT_SLIDE);
                String slideId = slideResource.getIdentifier();
                slideResource.setTitle(slideTitle);
                sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + slideId;
                slideResource.setSource(sourceUri);
                slideResource.setSourceContentType(IConstants.CT_IMAGE_PNG);
                store.update(slideResource, userUri);

                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
                store.storeBinaryResource(is, slideId);
                out.close();
                is.close();
                try {
                    ShareValue v = new ShareValue(ShareValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.SHARE_NAMESPACE + "slides", v);
                } catch (UnrecognizedValueTypeException e) {
                    // log this?  don't want to throw away everything, since this should never happen
                }
            }

            store.update(resource, userUri);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }

    } else {
        // must be a binary or unknown format, treat as black box
        // normally a service provider will understand this and parse it appropriately
        // however this server will accept any blank box resource

        try {
            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(uri);
            String id = resource.getIdentifier();
            resource.setTitle("Resource " + id);
            resource.setDescription("A binary resource");
            String sourceUri = getBaseUrl() + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());
            store.update(resource, userUri);

            store.storeBinaryResource(content, id);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    }
}

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

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D graphics2d = (Graphics2D) g;
    Dimension dimension = getSize();
    Insets insets = getInsets();/* ww w. ja v a  2s . c  o m*/
    java.awt.geom.Rectangle2D.Double double1 = new java.awt.geom.Rectangle2D.Double(insets.left, insets.top,
            dimension.getWidth() - (double) insets.left - (double) insets.right,
            dimension.getHeight() - (double) insets.top - (double) insets.bottom);
    double d = double1.getCenterX();
    double d1 = double1.getCenterY();
    java.awt.geom.Line2D.Double double2 = new java.awt.geom.Line2D.Double(d - 2D, d1 + 2D, d + 2D, d1 - 2D);
    java.awt.geom.Line2D.Double double3 = new java.awt.geom.Line2D.Double(d - 2D, d1 - 2D, d + 2D, d1 + 2D);
    graphics2d.setPaint(Color.red);
    graphics2d.draw(double2);
    graphics2d.draw(double3);
    graphics2d.setFont(font);
    graphics2d.setPaint(Color.black);
    if (rotate)
        TextUtilities.drawRotatedString(text, graphics2d, (float) d, (float) d1, anchor, angle, rotationAnchor);
    else
        TextUtilities.drawAlignedString(text, graphics2d, (float) d, (float) d1, anchor);
}

From source file:org.openfaces.component.chart.impl.renderers.GradientXYBarPainterAdapter.java

@Override
public void paintBarShadow(Graphics2D g2, XYBarRenderer renderer, int row, int column, RectangularShape bar,
        RectangleEdge base, boolean pegShadow) {
    // handle a special case - if the bar colour has alpha == 0, it is
    // invisible so we shouldn't draw any shadow
    Paint itemPaint = renderer.getItemPaint(row, column);
    if (itemPaint instanceof Color) {
        Color c = (Color) itemPaint;
        if (c.getAlpha() == 0) {
            return;
        }//from   ww  w . ja  v  a  2s  .  c  om
    }

    RectangularShape shadow = createShadow(bar, renderer.getShadowXOffset(), renderer.getShadowYOffset(), base,
            pegShadow);
    if (renderer instanceof XYBarRendererAdapter) {
        g2.setPaint(((XYBarRendererAdapter) renderer).getShadowPaint());
    }
    g2.fill(shadow);
}

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

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

    if (model instanceof ODE) {
        boolean pointBeyondPoincareSection;
        int numVar = model.getNVar();

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

        Stepper.Point2D result;//w ww.j  a v a 2s .  c  om

        g2.setPaint(plot.getPaint());

        parLower = domainAxis.getRange().getLowerBound();
        parUpper = domainAxis.getRange().getUpperBound();
        final double parStep;

        parStep = Math.abs(parUpper - parLower) / dataArea.getWidth();

        stepper.setAxes(variableIdx, variableIdx);

        state = STATE_RUNNING;

        for (index = parLower; index < parUpper; index += parStep) {

            fixedParameters[parameterIdx] = index;

            stepper.setParameters(fixedParameters);
            stepper.setInitialValue(initialValue);
            stepper.initialize();

            int h = 0;
            int transX, transY;

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

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

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

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

                //pointBeyondPoincareSection=positionWrtPoincareSection(currentPoint,coeff);
                result = stepper.getCurrentPoint2D();

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

                transY = (int) rangeAxis.valueToJava2D(result.getX(), dataArea, RectangleEdge.LEFT);

                h++;
                if (h > transients) {
                    g2.fillRect(transX, transY, 1, 1);
                }

            }

            if (!fixedInitialPoint) {
                stepper.getCurrentValue(initialValue);
            }

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

        state = STATE_FINISHED;
    } else {
        //the system is discrete
        ValueAxis domainAxis = plot.getDomainAxis();
        ValueAxis rangeAxis = plot.getRangeAxis();

        Stepper.Point2D result;

        g2.setPaint(plot.getPaint());

        parLower = domainAxis.getRange().getLowerBound();
        parUpper = domainAxis.getRange().getUpperBound();
        final double parStep;

        parStep = Math.abs(parUpper - parLower) / dataArea.getWidth();

        stepper.setAxes(variableIdx, variableIdx);

        state = STATE_RUNNING;

        for (index = parLower; index < parUpper; index += parStep) {

            fixedParameters[parameterIdx] = index;

            stepper.setParameters(fixedParameters);
            stepper.setInitialValue(initialValue);
            stepper.initialize();

            for (int h = 0; h < transients; h++) {
                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }

                stepper.step();
            }

            int transX, transY;
            for (int j = 0; j < iterations; j++) {

                stepper.step();

                result = stepper.getCurrentPoint2D();

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

                transY = (int) rangeAxis.valueToJava2D(result.getX(), dataArea, RectangleEdge.LEFT);

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

            if (!fixedInitialPoint) {
                stepper.getCurrentValue(initialValue);
            }

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

}