Example usage for java.awt Graphics2D drawRect

List of usage examples for java.awt Graphics2D drawRect

Introduction

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

Prototype

public void drawRect(int x, int y, int width, int height) 

Source Link

Document

Draws the outline of the specified rectangle.

Usage

From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java

private byte[] createImage(int width, int height, String text) throws IOException {
    if (width < 0) {
        width = random.nextInt(DEFAULT_MAX_IMAGE_WIDTH - DEFAULT_MIN_IMAGE_WIDTH) + DEFAULT_MIN_IMAGE_WIDTH;
    }/*from   www. j a  v a2 s  . co  m*/
    if (height < 0) {
        height = random.nextInt(DEFAULT_MAX_IMAGE_HEIGHT - DEFAULT_MIN_IMAGE_HEIGHT) + DEFAULT_MIN_IMAGE_HEIGHT;
    }

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = (Graphics2D) img.getGraphics();
    g2.setBackground(new Color(220, 220, 220));

    Dimension size;
    float fontSize = g2.getFont().getSize();
    // Make the text as large as possible.
    do {
        g2.setFont(g2.getFont().deriveFont(fontSize));
        FontMetrics metrics = g2.getFontMetrics(g2.getFont());
        int hgt = metrics.getHeight();
        int adv = metrics.stringWidth(text);
        size = new Dimension(adv + 2, hgt + 2);
        fontSize = fontSize + 1f;
    } while (size.width < Math.round(0.9 * width) && size.height < Math.round(0.9 * height));

    g2.setColor(Color.DARK_GRAY);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.drawString(text, (width - size.width) / 2, (height - size.height) / 2);
    g2.setColor(Color.LIGHT_GRAY);
    g2.drawRect(0, 0, width - 1, height - 1);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(width * height);
    ImageIO.write(img, "png", baos);
    baos.flush();
    byte[] rawBytes = baos.toByteArray();
    baos.close();

    return rawBytes;
}

From source file:net.geoprism.dashboard.DashboardMap.java

/**
 * Builds an image layer of all the layers in a SavedMap.
 * //from   w w w .  ja  v a  2  s  . co  m
 * @mapWidth
 * @mapHeight
 */
private BufferedImage getLegendExportCanvas(int mapWidth, int mapHeight) {
    int padding = 2;
    BufferedImage base = null;
    Graphics mapBaseGraphic = null;
    Color innerBackgroundColor = Color.darkGray;
    Color outerBorderColor = Color.black;
    int legendTopPlacement = 0;
    int legendLeftPlacement = 0;
    int widestLegend = 0;
    int legendXPosition = 0;
    int legendYPosition = 0;

    List<? extends DashboardLayer> layers = this.getAllHasLayer().getAll();

    try {
        base = new BufferedImage(mapWidth, mapHeight, BufferedImage.TYPE_INT_ARGB);
        mapBaseGraphic = base.getGraphics();
        mapBaseGraphic.drawImage(base, 0, 0, null);

        // Generates map overlays and combines them into a single map image
        for (DashboardLayer layer : layers) {
            if (layer.getDisplayInLegend()) {
                Graphics2D titleBaseGraphic = null;
                Graphics2D iconGraphic = null;

                String requestURL = getLegendURL(layer);

                try {
                    // handle color graphics and categories
                    BufferedImage titleBase = getLegendTitleImage(layer);
                    titleBaseGraphic = titleBase.createGraphics();
                    int paddedTitleWidth = titleBase.getWidth();
                    int paddedTitleHeight = titleBase.getHeight();

                    BufferedImage icon = getImageFromGeoserver(requestURL);
                    int iconHeight = icon.getHeight();
                    int iconWidth = icon.getWidth();
                    int paddedIconWidth = iconWidth + (padding * 2);
                    int paddedIconHeight = iconHeight + (padding * 2);

                    int fullWidth = paddedIconWidth + paddedTitleWidth;
                    int fullHeight;
                    if (paddedIconHeight >= paddedTitleHeight) {
                        fullHeight = paddedIconHeight;
                    } else {
                        fullHeight = paddedTitleHeight;
                    }

                    DashboardLegend legend = layer.getDashboardLegend();
                    if (legend.getGroupedInLegend()) {
                        if (legendTopPlacement + fullHeight >= mapHeight) {
                            legendLeftPlacement = widestLegend + legendLeftPlacement + padding;
                            legendTopPlacement = 0; // reset so 2nd column legends start at the top row
                        }
                        legendXPosition = legendLeftPlacement + padding;
                        legendYPosition = legendTopPlacement + padding;
                    } else {
                        legendXPosition = (int) Math.round((double) legend.getLegendXPosition());
                        legendYPosition = (int) Math.round((double) legend.getLegendYPosition());
                    }

                    BufferedImage legendBase = new BufferedImage(fullWidth + (padding * 2),
                            fullHeight + (padding * 2), BufferedImage.TYPE_INT_ARGB);
                    Graphics2D legendBaseGraphic = legendBase.createGraphics();
                    legendBaseGraphic.setColor(innerBackgroundColor);
                    legendBaseGraphic.fillRect(0, 0, fullWidth, fullHeight);
                    legendBaseGraphic.setColor(outerBorderColor);
                    legendBaseGraphic.setStroke(new BasicStroke(5));
                    legendBaseGraphic.drawRect(0, 0, fullWidth, fullHeight);

                    legendBaseGraphic.drawImage(icon, padding, padding, paddedIconWidth, paddedIconHeight,
                            null);
                    legendBaseGraphic.drawImage(titleBase, paddedIconWidth + (padding * 2),
                            (fullHeight / 2) - (paddedTitleHeight / 2), paddedTitleWidth, paddedTitleHeight,
                            null);
                    mapBaseGraphic.drawImage(legendBase, legendXPosition, legendYPosition, fullWidth,
                            fullHeight, null);

                    if (legend.getGroupedInLegend()) {
                        legendTopPlacement = legendTopPlacement + fullHeight + padding;
                    }

                    if (fullWidth > widestLegend) {
                        widestLegend = fullWidth;
                    }
                } finally {
                    if (titleBaseGraphic != null) {
                        titleBaseGraphic.dispose();
                    }

                    if (iconGraphic != null) {
                        iconGraphic.dispose();
                    }
                }
            }
        }
    } finally {
        mapBaseGraphic.dispose();
    }

    return base;
}

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 w w w . ja v  a 2 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:tufts.vue.RichTextBox.java

public void draw(DrawContext dc) {
    if (TestDebug)
        out("draw");

    if (getParent() != null)
        System.err.println("Warning: 2nd draw of an AWT drawn component!");

    //todo: could try saving current translation or coordinates here,
    // so have EXACT last position painted at.  Tho we really should
    // be able to compute it... problem is may not be at integer
    // boundry at current translation, but have to be when we add it
    // to the map -- tho hey, LWNode could force integer boundry
    // when setting the translation before painting us.

    if (DEBUG.BOXES && DEBUG.META) {
        if (lwc.getLabel().indexOf('\n') < 0) {
            TextRow r = new TextRow(lwc.getLabel(), lwc.getFont(), dc.g.getFontRenderContext());
            dc.g.setColor(Color.lightGray);
            r.draw(dc, 0, 0);// w  w w  . ja v a  2  s  .  co m
        }
    }

    boolean restoreTextColor = false;

    //         if (dc.isBlackWhiteReversed() &&
    //             (dc.isPresenting() || lwc.isTransparent() /*|| isBlack(lwc.getFillColor())*/) &&
    //             isBlack(lwc.getTextColor())) {
    //             //System.out.println("reversing color to white for " + this);
    //             setDocumentColor(Color.white);
    //             inverted = true;
    //         } else
    //             inverted = false;

    if (dc.isPresenting() && lwc.isTransparent()) {
        // if the text color equals the background color when in a presentation
        // (e.g. the master slide has a black background), and the text box
        // has to fill of it's own for contrast, then temporarily swap
        // the text color to white or black so it can be seen.
        if (lwc.mTextColor.equals(dc.getBackgroundFill())) {
            restoreTextColor = true;
            if (lwc.mTextColor.brightness() > 0.5) {
                setDocumentColor(DEBUG.Enabled ? Color.blue : Color.black);
            } else {
                setDocumentColor(DEBUG.Enabled ? Color.green : Color.white);
            }
        }
    }

    //super.paintBorder(g);

    //         // As of least Mac OS X 10.4.10 w/JVM 1.5.0_07 on 2007-08-13,
    //         // it appears there's no way to NOT render anti-aliased text,
    //         // unless there's some other way to override it in JTextPane/JTextComponent
    //         // Not a big deal -- we'd only like the option for a slight speed up
    //         // during animations.
    //         dc.g.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
    //                               java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    //         dc.g.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING,
    //                               java.awt.RenderingHints.VALUE_ANTIALIAS_OFF);
    //         // Even this doesn't appear to help:
    //         putClientProperty(com.sun.java.swing.SwingUtilities2.AA_TEXT_PROPERTY_KEY, Boolean.FALSE);

    super.paintComponent(dc.g);
    //super.paint(g);

    if (restoreTextColor) {
        // return document color to black
        setDocumentColor(lwc.mTextColor.get());
    }

    // draw a border for links -- why?
    // and even if, better to handle in LWLink
    /*
    if (lwc instanceof LWLink) {
    Dimension s = getSize();
    if (lwc.isSelected())
        g.setColor(COLOR_SELECTION);
    else
        g.setColor(Color.gray);
    g.setStroke(MinStroke);
    g.drawRect(0,0, s.width-1, s.height-2);
    }
    */

    Graphics2D g = dc.g;
    if (DEBUG.BOXES) {
        Dimension s = getPreferredSize();
        g.setColor(Color.red);
        dc.setAbsoluteStroke(0.5);
        //g.setStroke(MinStroke);
        g.drawRect(0, 0, s.width, s.height);
        //g.drawRect(0,0, s.width-1, s.height);
    }

    //s = getMinimumSize();
    //g.setColor(Color.red);
    //g.setStroke(new BasicStroke(1/8f));
    //g.drawRect(0,0, s.width, s.height);

    if (DEBUG.BOXES || getParent() != null) {
        Dimension s = getSize();
        g.setColor(Color.blue);
        dc.setAbsoluteStroke(0.5);
        //g.setStroke(MinStroke);
        g.drawRect(0, 0, s.width, s.height);
        //g.drawRect(0,0, s.width-1, s.height);
    }

}

From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

private static void drawSelection(final Graphics2D g, final MindMapPanelConfig cfg,
        final List<Topic> selectedTopics) {
    if (selectedTopics != null && !selectedTopics.isEmpty()) {
        g.setColor(cfg.getSelectLineColor());
        final Stroke dashed = new BasicStroke(cfg.safeScaleFloatValue(cfg.getSelectLineWidth(), 0.1f),
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0,
                new float[] { cfg.safeScaleFloatValue(1.0f, 0.1f), cfg.safeScaleFloatValue(4.0f, 0.1f) }, 0);
        g.setStroke(dashed);/* w w w  .  ja  v  a  2 s.c  o m*/
        final double selectLineGap = (double) cfg.safeScaleFloatValue(cfg.getSelectLineGap(), 0.05f);
        final double selectLineGapX2 = selectLineGap + selectLineGap;

        for (final Topic s : selectedTopics) {
            final AbstractElement e = (AbstractElement) s.getPayload();
            if (e != null) {
                final int x = (int) Math.round(e.getBounds().getX() - selectLineGap);
                final int y = (int) Math.round(e.getBounds().getY() - selectLineGap);
                final int w = (int) Math.round(e.getBounds().getWidth() + selectLineGapX2);
                final int h = (int) Math.round(e.getBounds().getHeight() + selectLineGapX2);
                g.drawRect(x, y, w, h);
            }
        }
    }
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    try {/*www. j  a  v a2  s.c o m*/
        Graphics2D g2d = (Graphics2D) g;
        g2d.clearRect(0, 0, getWidth(), getHeight());
        g2d.drawImage(mBuffer, 0, 0, null);

        if (iCurrentView == ID_MINIMAP) {
            g2d.setColor(Color.YELLOW);

            int mapWidth = rVisiblePart.width;
            int mapHeight = rVisiblePart.height;

            int w = (int) Math.rint(((double) getWidth() / mapWidth) * (double) iWidth);
            int h = (int) Math.rint(((double) getHeight() / mapHeight) * (double) iHeight);

            double posX = ((double) getWidth() / mapWidth * (double) (iX - rVisiblePart.x)) - w / 2;
            double posY = ((double) getHeight() / mapHeight * (double) (iY - rVisiblePart.y)) - h / 2;

            g2d.drawRect((int) Math.rint(posX), (int) Math.rint(posY), w, h);

            if (iCurrentCursor == ImageManager.CURSOR_SHOT) {
                if (rDrag != null) {
                    g2d.setColor(Color.ORANGE);
                    g2d.drawRect((int) rDrag.getMinX(), (int) rDrag.getMinY(),
                            (int) (rDrag.getWidth() - rDrag.getX()), (int) (rDrag.getHeight() - rDrag.getY()));
                }
            } else if (iCurrentCursor == ImageManager.CURSOR_ZOOM) {
                if (rDrag != null) {
                    g2d.setColor(Color.CYAN);
                    g2d.drawRect((int) rDrag.getX(), (int) rDrag.getY(),
                            (int) (rDrag.getWidth() - rDrag.getX()),
                            (int) ((rDrag.getWidth() - rDrag.getX()) * ((double) getHeight()) / getWidth()));
                }
            }
        }

        if (showControls) {
            //g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .2f));
            Rectangle r = minimapButtons.get(ID_MINIMAP);
            g2d.setColor(Color.WHITE);
            Point menuPos = r.getLocation();
            menuPos.translate(-2, -2);
            //draw border
            g2d.fillRect(menuPos.x, menuPos.y, 88, 30);
            g2d.setColor(Color.BLACK);
            //check if mouse is inside minimap button
            if (getMousePosition() != null && r.contains(getMousePosition())) {
                g2d.setColor(Color.YELLOW);
                g2d.fillRect(r.x, r.y, r.width, r.height);
                g2d.setColor(Color.BLACK);
            }
            g2d.drawImage(minimapIcons.get(ID_MINIMAP), r.x, r.y, null);
            g2d.drawRect(r.x, r.y, r.width, r.height);

            r = minimapButtons.get(ID_ALLY_CHART);
            //check if mouse is inside ally chart button
            if (getMousePosition() != null && r.contains(getMousePosition())) {
                g2d.setColor(Color.YELLOW);
                g2d.fillRect(r.x, r.y, r.width, r.height);
                g2d.setColor(Color.BLACK);
            }
            g2d.drawImage(minimapIcons.get(ID_ALLY_CHART), r.x, r.y, null);
            g2d.drawRect(r.x, r.y, r.width, r.height);

            r = minimapButtons.get(ID_TRIBE_CHART);
            //check if mouse is inside tribe chart button
            if (getMousePosition() != null && r.contains(getMousePosition())) {
                g2d.setColor(Color.YELLOW);
                g2d.fillRect(r.x, r.y, r.width, r.height);
                g2d.setColor(Color.BLACK);

            }
            g2d.drawImage(minimapIcons.get(ID_TRIBE_CHART), r.x, r.y, null);
            g2d.drawRect(r.x, r.y, r.width, r.height);
        }
        g2d.dispose();
    } catch (Exception e) {
        logger.error("Failed painting Minimap", e);
    }
}

From source file:org.apache.ofbiz.common.CommonEvents.java

public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
    try {//www .j ava 2s  .com
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"),
                "default");
        final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha",
                "captcha." + captchaSizeConfigName, delegator);
        final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
        final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored

        final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
        final int height = Integer.parseInt(captchaSizeConfigs[1]);
        final int width = Integer.parseInt(captchaSizeConfigs[2]);
        final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6);
        final char[] availableChars = EntityUtilProperties
                .getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();

        //It is possible to pass the font size, image width and height with the request as well
        Color backgroundColor = Color.gray;
        Color borderColor = Color.DARK_GRAY;
        Color textColor = Color.ORANGE;
        Color circleColor = new Color(160, 160, 160);
        Font textFont = new Font("Arial", Font.PLAIN, fontSize);
        int circlesToDraw = 6;
        float horizMargin = 20.0f;
        double rotationRange = 0.7; // in radians
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

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

        g.setColor(backgroundColor);
        g.fillRect(0, 0, width, height);

        //Generating some circles for background noise
        g.setColor(circleColor);
        for (int i = 0; i < circlesToDraw; i++) {
            int circleRadius = (int) (Math.random() * height / 2.0);
            int circleX = (int) (Math.random() * width - circleRadius);
            int circleY = (int) (Math.random() * height - circleRadius);
            g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
        }
        g.setColor(textColor);
        g.setFont(textFont);

        FontMetrics fontMetrics = g.getFontMetrics();
        int maxAdvance = fontMetrics.getMaxAdvance();
        int fontHeight = fontMetrics.getHeight();

        String captchaCode = RandomStringUtils.random(6, availableChars);

        float spaceForLetters = -horizMargin * 2 + width;
        float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);

        for (int i = 0; i < captchaCode.length(); i++) {

            // this is a separate canvas used for the character so that
            // we can rotate it independently
            int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
            int charDim = Math.max(maxAdvance, fontHeight);
            int halfCharDim = (charDim / 2);

            BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
            Graphics2D charGraphics = charImage.createGraphics();
            charGraphics.translate(halfCharDim, halfCharDim);
            double angle = (Math.random() - 0.5) * rotationRange;
            charGraphics.transform(AffineTransform.getRotateInstance(angle));
            charGraphics.translate(-halfCharDim, -halfCharDim);
            charGraphics.setColor(textColor);
            charGraphics.setFont(textFont);

            int charX = (int) (0.5 * charDim - 0.5 * charWidth);
            charGraphics.drawString("" + captchaCode.charAt(i), charX,
                    ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));

            float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
            int y = ((height - charDim) / 2);

            g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);

            charGraphics.dispose();
        }
        // Drawing the image border
        g.setColor(borderColor);
        g.drawRect(0, 0, width - 1, height - 1);
        g.dispose();
        response.setContentType("image/jpeg");
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        HttpSession session = request.getSession();
        Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
        if (captchaCodeMap == null) {
            captchaCodeMap = new HashMap<String, String>();
            session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
        }
        captchaCodeMap.put(captchaCodeId, captchaCode);
    } catch (Exception ioe) {
        Debug.logError(ioe.getMessage(), module);
    }
    return "success";
}

From source file:org.ofbiz.common.CommonEvents.java

public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
    try {/*from  w ww  . j  a  v a 2 s  . c om*/
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"),
                "default");
        final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha.properties",
                "captcha." + captchaSizeConfigName, delegator);
        final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
        final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored

        final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
        final int height = Integer.parseInt(captchaSizeConfigs[1]);
        final int width = Integer.parseInt(captchaSizeConfigs[2]);
        final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha.properties",
                "captcha.code_length", 6);
        final char[] availableChars = EntityUtilProperties
                .getPropertyValue("captcha.properties", "captcha.characters", delegator).toCharArray();

        //It is possible to pass the font size, image width and height with the request as well
        Color backgroundColor = Color.gray;
        Color borderColor = Color.DARK_GRAY;
        Color textColor = Color.ORANGE;
        Color circleColor = new Color(160, 160, 160);
        Font textFont = new Font("Arial", Font.PLAIN, fontSize);
        int circlesToDraw = 6;
        float horizMargin = 20.0f;
        double rotationRange = 0.7; // in radians
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

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

        g.setColor(backgroundColor);
        g.fillRect(0, 0, width, height);

        //Generating some circles for background noise
        g.setColor(circleColor);
        for (int i = 0; i < circlesToDraw; i++) {
            int circleRadius = (int) (Math.random() * height / 2.0);
            int circleX = (int) (Math.random() * width - circleRadius);
            int circleY = (int) (Math.random() * height - circleRadius);
            g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
        }
        g.setColor(textColor);
        g.setFont(textFont);

        FontMetrics fontMetrics = g.getFontMetrics();
        int maxAdvance = fontMetrics.getMaxAdvance();
        int fontHeight = fontMetrics.getHeight();

        String captchaCode = RandomStringUtils.random(6, availableChars);

        float spaceForLetters = -horizMargin * 2 + width;
        float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);

        for (int i = 0; i < captchaCode.length(); i++) {

            // this is a separate canvas used for the character so that
            // we can rotate it independently
            int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
            int charDim = Math.max(maxAdvance, fontHeight);
            int halfCharDim = (charDim / 2);

            BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
            Graphics2D charGraphics = charImage.createGraphics();
            charGraphics.translate(halfCharDim, halfCharDim);
            double angle = (Math.random() - 0.5) * rotationRange;
            charGraphics.transform(AffineTransform.getRotateInstance(angle));
            charGraphics.translate(-halfCharDim, -halfCharDim);
            charGraphics.setColor(textColor);
            charGraphics.setFont(textFont);

            int charX = (int) (0.5 * charDim - 0.5 * charWidth);
            charGraphics.drawString("" + captchaCode.charAt(i), charX,
                    ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));

            float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
            int y = ((height - charDim) / 2);

            g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);

            charGraphics.dispose();
        }
        // Drawing the image border
        g.setColor(borderColor);
        g.drawRect(0, 0, width - 1, height - 1);
        g.dispose();
        response.setContentType("image/jpeg");
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        HttpSession session = request.getSession();
        Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
        if (captchaCodeMap == null) {
            captchaCodeMap = new HashMap<String, String>();
            session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
        }
        captchaCodeMap.put(captchaCodeId, captchaCode);
    } catch (Exception ioe) {
        Debug.logError(ioe.getMessage(), module);
    }
    return "success";
}

From source file:pl.edu.icm.visnow.system.main.VisNow.java

private static void renderSplashFrame(float progress, String loadText, String bottomTextUpperLine,
        String bottomTextLowerLine) {
    if (splash == null) {
        return;/*  ww  w  .  j  ava 2 s . c o  m*/
    }

    try {
        Graphics2D g = splash.createGraphics();
        if (g == null) {
            return;
        }

        if (!splash.isVisible())
            return;

        Rectangle bounds = splash.getBounds();
        Font f = g.getFont();
        FontMetrics fm = g.getFontMetrics(f);
        java.awt.geom.Rectangle2D rect = fm.getStringBounds(loadText, g);
        int texth = (int) Math.ceil(rect.getHeight());
        g.setComposite(AlphaComposite.Clear);
        //g.setColor(Color.RED);
        g.fillRect(PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN - texth - 5,
                bounds.width - PROGRESS_TEXT_X_POSITION, texth + 10);

        g.setFont(lowerLineFont);
        fm = g.getFontMetrics(g.getFont());
        rect = fm.getStringBounds(bottomTextLowerLine, g);
        int lowerLineTextHeight = (int) Math.ceil(rect.getHeight());
        g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN - lowerLineTextHeight - 5,
                bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10);

        g.setFont(f);
        fm = g.getFontMetrics(g.getFont());
        rect = fm.getStringBounds(bottomTextUpperLine, g);
        texth = (int) Math.ceil(rect.getHeight());
        g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN - texth - 5,
                bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10);

        g.setPaintMode();
        //        g.setColor(Color.BLACK);
        g.setColor(new Color(0, 75, 50));
        g.drawString(loadText, PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN);
        g.drawString(bottomTextUpperLine, BOTTOM_TEXT_X_MARGIN,
                bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN);
        g.setFont(lowerLineFont);
        g.drawString(bottomTextLowerLine, BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN);
        g.setFont(f);

        //        g.setColor(Color.BLACK);
        g.setColor(new Color(0, 150, 100));
        g.drawRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN,
                bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT);
        int progressWidth = bounds.width - 2 * PROGRESS_BAR_X_MARGIN;
        int done = (int) (progressWidth * progress);
        g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN, PROGRESS_BAR_X_MARGIN + done,
                PROGRESS_BAR_HEIGHT);
        if (progress >= 1.0f) {
            g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN,
                    bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT);
        }

        splash.update();
    } catch (IllegalStateException ex) {
    }
}

From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java

private void renderRange(LongRange pRange, LongRange pStartRange, LongRange pArriveRange, boolean pIsStartRange,
        boolean pIsArriveRange, Graphics2D pG2D, TimeSpan pSpanForRange, HashMap<String, Object> pPopupInfo) {
    int rangeStart = 0;
    int rangeWidth = 0;

    if (pRange.overlapsRange(pStartRange)) {
        //start range rendering
        long startDelta = pStartRange.getMinimumLong();
        rangeStart = Math.round((pRange.getMinimumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE);
        // int rangeEnd = Math.round((pRange.getMaximumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE);
        rangeWidth = Math//w  w  w  .j av  a 2  s  .c o  m
                .round((pRange.getMaximumLong() - pRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE);
    } else if (pRange.overlapsRange(pArriveRange)) {
        //end range rendering
        long startDelta = pStartRange.getMinimumLong();
        rangeStart = Math.round((pRange.getMinimumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE);
        // int rangeEnd = Math.round((pRange.getMaximumLong() - arriveDelta) / DateUtils.MILLIS_PER_MINUTE);
        rangeWidth = Math
                .round((pRange.getMaximumLong() - pRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE);
    }
    //correct small widths
    if (rangeWidth == 0) {
        rangeWidth = 5;
    }

    long max = Math.round(
            (pArriveRange.getMaximumLong() - pStartRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE);

    if (rangeStart > max) {
        return;
    }

    SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy HH:mm:ss");
    String labelString = "";
    if (pSpanForRange != null) {
        labelString = pSpanForRange.toString();
    } else {
        labelString = f.format(new Date(pRange.getMinimumLong())) + " bis "
                + f.format(new Date(pRange.getMaximumLong()));
    }
    Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(labelString, pG2D);
    if (pIsStartRange) {
        pG2D.setColor(Color.RED);
        pG2D.fillRect(rangeStart, 20, rangeWidth, 20);
        pG2D.setColor(Color.BLACK);
        pG2D.drawRect(rangeStart, 20, rangeWidth, 20);
        pG2D.setColor(Color.RED);
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 14.0f));
        pG2D.drawString(labelString, rangeStart, (int) labelBounds.getHeight());
    } else if (pIsArriveRange) {
        pG2D.setColor(Color.GREEN.darker());
        pG2D.fillRect(rangeStart, 20, rangeWidth, 20);
        pG2D.setColor(Color.BLACK);
        pG2D.drawRect(rangeStart, 20, rangeWidth, 20);
        pG2D.setColor(Color.GREEN.darker());
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 14.0f));
        pG2D.drawString(labelString, rangeStart, (int) labelBounds.getHeight() + 40);
    } else {
        pG2D.fillRect(rangeStart, 20, rangeWidth, 20);
        pG2D.setColor(Color.BLACK);
        pG2D.drawRect(rangeStart, 20, rangeWidth, 20);
        Point loc = getMousePosition();
        if (loc != null && new Rectangle(rangeStart, 20, rangeWidth, 20).contains(loc)) {
            pPopupInfo.put("popup.location", loc);
            pPopupInfo.put("popup.label", labelString);
            pPopupInfo.put("active.range", pRange);
            pPopupInfo.put("span.for.range", pSpanForRange);

        }
    }
}