Example usage for java.awt Graphics2D drawString

List of usage examples for java.awt Graphics2D drawString

Introduction

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

Prototype

public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);

Source Link

Document

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

Usage

From source file:Main.java

public int print(Graphics g, PageFormat Pf, int pageIndex) throws PrinterException {
    if (pageIndex > 0)
        return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.setFont(sFont);//from w  w w. j  av a 2 s  . c o m
    g2.setPaint(Color.black);
    g2.drawString("Save a tree!", 96, 144);
    return PAGE_EXISTS;
}

From source file:Main.java

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

    Font f = new Font("Arial", Font.PLAIN, 48);
    g2.setFont(f);//ww  w .  j  a  v  a  2  s. c om

    g2.drawString("www.java2s.com", 10, 60);

    RenderingHints rh = g2.getRenderingHints();
    rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHints(rh);

    g2.drawString("Antialiased text", 10, 120);
}

From source file:MainClass.java

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

    Font f = new Font("Arial", Font.PLAIN, 48);
    g2.setFont(f);//from   w  ww.  j a  va2  s  .c  o  m

    g2.drawString("www.java2s.com", 10, 60);

    RenderingHints rh = g2.getRenderingHints();
    rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHints(rh);

    g2.drawString("Antialiased text", 10, 120);

}

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

public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
    try {/*from w  w  w.j  av  a2  s. co  m*/
        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  a2s.co  m*/
        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:Main.java

@Override
public void paintComponent(Graphics g) {
    if (g instanceof Graphics2D) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.drawString("This is gona be awesome", 70, 20);
    }//from   w  w w  .  j  av  a2 s. c o  m
}

From source file:MainClass.java

public int print(Graphics g, PageFormat pf, int pageIndex) {
    if (pageIndex != 0)
        return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.setFont(new Font("Serif", Font.PLAIN, 36));
    g2.setPaint(Color.black);//  w ww  .  ja va 2s .c o  m
    g2.drawString("www.java2s.com", 100, 100);
    Rectangle2D outline = new Rectangle2D.Double(pf.getImageableX(), pf.getImageableY(), pf.getImageableWidth(),
            pf.getImageableHeight());
    g2.draw(outline);
    return PAGE_EXISTS;
}

From source file:BasicDraw.java

public void paint(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;

    AffineTransform at = new AffineTransform();
    at.setToRotation(Math.PI / 4.0);
    g2d.setTransform(at);// www.java 2  s . c o  m
    g2d.drawString("aString", 200, 100);

}

From source file:DrawStringI18N.java

public void paint(Graphics g) {
    Graphics2D graphics2D = (Graphics2D) g;
    GraphicsEnvironment.getLocalGraphicsEnvironment();
    graphics2D.setFont(new Font("LucidaSans", Font.PLAIN, 40));
    graphics2D.drawString("\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD", 50, 75);
}

From source file:controle.JfreeChartController.java

@PostConstruct
public void init() {
    try {//www. java2  s. c  o  m
        //Graphic Text
        BufferedImage bufferedImg = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bufferedImg.createGraphics();
        g2.drawString("This is a text", 0, 10);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImg, "png", os);
        graphicText = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");

        //Chart
        JFreeChart jfreechart = ChartFactory.createLineChart("cosseno", "X", "Y", createDataset());
        File chartFile = new File("dynamichart");
        ChartUtilities.saveChartAsPNG(chartFile, jfreechart, 800, 400);
        chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/png");
    } catch (Exception e) {
        e.printStackTrace();
    }
}