Example usage for java.awt Graphics2D setFont

List of usage examples for java.awt Graphics2D setFont

Introduction

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

Prototype

public abstract void setFont(Font font);

Source Link

Document

Sets this graphics context's font to the specified font.

Usage

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

/**
 * //ww  w . j  av a  2  s .co  m
 */
public void generate() {
    Rectangle rect = getPanel().getParent().getBounds();
    System.out.println("MAIN[" + rect + "]");
    if (rect.width == 0 || rect.height == 0) {
        return;
    }

    BufferedImage bufImage = new BufferedImage(rect.width, rect.height,
            (doPNG ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB));
    Graphics2D g2 = bufImage.createGraphics();
    if (!doPNG) {
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, rect.width, rect.height);
    }
    g2.setRenderingHints(createTextRenderingHints());
    g2.setFont(tblTracker.getFont());
    getPanel().getParent().paint(g2);

    g2.dispose();

    Component stop = getPanel().getParent();
    Point p = new Point(0, 0);
    calcLoc(p, getPanel().getMainTable(), stop);

    String name = StringUtils.substringAfterLast(getPanel().getMainTable().getClassName(), ".");
    DBTableInfo tblInfo = DBTableIdMgr.getInstance().getByShortClassName(name);
    String fName = schemaDir.getAbsolutePath() + File.separator + name;
    try {
        String origName = fName;
        int i = 1;
        while (pngNameHash.contains(fName)) {
            fName = origName + i;
        }
        pngNameHash.add(fName);

        File html = new File(fName + ".html");
        BufferedWriter output = new BufferedWriter(new FileWriter(html));

        int index = mapTemplate.indexOf(contentTag);
        String subContent = mapTemplate.substring(0, index);
        output.write(StringUtils.replace(subContent, "<!-- Title -->", tblInfo.getTitle()));

        File imgFile = new File(fName + (doPNG ? ".png" : ".jpg"));
        output.write("<map name=\"schema\" id=\"schema\">\n");

        Vector<ERDTable> nList = mainPanel.isRoot() ? tblTracker.getTreeAsList(mainPanel.getMainTable())
                : getPanel().getRelTables();
        for (ERDTable erdt : nList) {
            p = new Point(0, 0);
            calcLoc(p, erdt, stop);
            Dimension s = erdt.getSize();
            String linkname = StringUtils.substringAfterLast(erdt.getClassName(), ".");
            output.write("<area shape=\"rect\" coords=\"" + p.x + "," + p.y + "," + (p.x + s.width) + ","
                    + (p.y + s.height) + "\" href=\"" + linkname + ".html\"/>\n");
        }

        output.write("</map>\n");
        output.write("<img border=\"0\" usemap=\"#schema\" src=\"" + imgFile.getName() + "\"/>\n");

        output.write(mapTemplate.substring(index + contentTag.length() + 1, mapTemplate.length()));

        output.close();

        File oFile = new File(schemaDir + File.separator + imgFile.getName());
        System.out.println(oFile.getAbsolutePath());
        if (doPNG) {
            ImageIO.write(bufImage, "PNG", oFile);
        } else {
            writeJPEG(oFile, bufImage, 0.75f);
        }
        //ImageIO.write(bufImage, "JPG", new File(schemaDir + File.separator + imgFile.getName()+".jpg"));

    } catch (Exception e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e);
        e.printStackTrace();
    }
}

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;
    }//  w w w. j  a va  2 s  .c om
    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:gg.msn.ui.panel.MainPanel.java

@Override
public void paint(Graphics g) {
    super.paint(g);
    try {//from w ww  .jav  a  2  s  .  c o  m
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        //render per utenti Facebook
        if (ChatClientView.protocol.equals(ChatClientView.FACEBOOK_PROTOCOL)) {
            final FacebookUser user = (FacebookUser) value;
            int textY = (getHeight() / 2) + (g2.getFont().getSize() / 2);

            //name string
            g2.setFont(list.getFont());
            g2.drawString(user.name, WHITE_SPACE + IMAGE_LATE + 3, textY);

            //status string
            //                g2.setFont(list.getFont());
            //                g2.drawString(user.status, WHITE_SPACE + IMAGE_LATE + 3, textY);

            //icon
            ImageIcon icon = user.portrait;
            //log.debug("icon [" + icon + "]");
            //ImageIcon scaledIcon = new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_AREA_AVERAGING));
            g2.drawImage(icon.getImage(), WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE,
                    IMAGE_LATE, null);
            //                 g2.setColor(Color.WHITE);
            //                g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE, IMAGE_LATE, ARC_SIZE, ARC_SIZE);
            //                g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - ((IMAGE_LATE+1) / 2), IMAGE_LATE+1, IMAGE_LATE+1, ARC_SIZE, ARC_SIZE);
            //                g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - ((IMAGE_LATE+2) / 2), IMAGE_LATE+2, IMAGE_LATE+2, ARC_SIZE, ARC_SIZE);
            //render per utenti Client
            //                log.debug("user status [" + user.status + "]");
            //                log.debug("user online status [" + user.onlineStatus + "]");
            if (StringUtils.equals(user.status, FacebookUser.STATUS_ONLINE)) {
                g2.setColor(Color.GREEN);
                g2.fillOval(getWidth() - STATUS_ICON_OFFSET, (getHeight() / 2) - (STATUS_ICON_WIDTH / 2),
                        STATUS_ICON_WIDTH, STATUS_ICON_WIDTH);
            } else {
                g2.setColor(Color.GRAY);
                g2.fillOval(getWidth() - STATUS_ICON_OFFSET, (getHeight() / 2) - (STATUS_ICON_WIDTH / 2),
                        STATUS_ICON_WIDTH, STATUS_ICON_WIDTH);
            }

        } else {
            g2.setFont(list.getFont());
            int textY = (getHeight() / 2) + (g2.getFont().getSize() / 2);

            Client client = (Client) value;
            //                setText((client).getNick());
            ImageIcon icon = null;
            try {
                new ImageIcon(client.getImage());
            } catch (Exception e) {
                //                    log.debug("immgine non presente");
                icon = ThemeManager.getTheme().get(ThemeManager.USER_ICON);
            }
            g2.drawString(client.getNick(), WHITE_SPACE + IMAGE_LATE + 3, textY);
            //log.debug("icon [" + icon + "]");
            //ImageIcon scaledIcon = new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_AREA_AVERAGING));
            g2.drawImage(icon.getImage(), WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE,
                    IMAGE_LATE, null);

            //                setFont(list.getFont());
            //                setIcon(scaledIcon);
        }
    } catch (Exception e) {
        log.warn(e);
    }

}

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

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

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

    if (showNavigation) {// && !isHierarchicalZoomInProgress()) {

        PBounds bounds = getBoundsReference();

        int x = (int) bounds.getX();
        int y = (int) bounds.getY();
        int width = (int) bounds.getWidth();
        int height = (int) bounds.getHeight();

        g.setColor(Constants.Color.COLOR_SHAPE_BACKGROUND);
        if (isRenderPrimitiveRect())
            g.fillRect(x, y, width, 60);
        else {// ww w .  j ava2 s.com
            g.clearRect(x, y, width, 60);
            g.fillRoundRect(x, y, width, 60, 25, 25);
        }

        g.setColor(Constants.Color.COLOR_SHAPE_BORDER);
        if (isRenderPrimitiveRect())
            g.drawRect(x, y, width, 60);
        else
            g.drawRoundRect(x, y, width, 60, 25, 25);

        g.setFont(fontBreadcrumb);

        if (titleBounds == null) {
            FontMetrics fm = g.getFontMetrics();
            titleBounds = new Rectangle2D.Double(bounds.getX() + 455 + titleGap,
                    bounds.getY() + 25 - fm.getHeight(), FontUtils.getWidthOfText(fm, getTitle()) + 10,
                    fm.getHeight() + 5);
        }

        // Font font = internalFont.deriveFont(3.2f);
        for (int i = 0; i < 3; i++) {
            if (isRenderPrimitiveRect())
                g.fillRect((int) (bounds.getX() + 430), (int) bounds.getY() + i * 15 + 10, 5, 10);
            else
                g.fillOval((int) (bounds.getX() + 430), (int) bounds.getY() + i * 15 + 10, 5, 10);
        }

        if (!ShapeUtils.isApparent(titleInputWrapper)) {
            g.drawString(getTitle(), (int) (bounds.getX() + 460 + titleGap), (int) (bounds.getY() + 25));
        }

        if (croppedBreadcrumb == null) {
            croppedBreadcrumb = FontUtils.createCroppedLabelIfNecessary(g.getFontMetrics(), getBreadcrumb(),
                    (int) bounds.getWidth() * 10 - 450);
        }
        g.drawString(croppedBreadcrumb, (int) (bounds.getX() + 460), (int) (bounds.getY() + 50));
    }
}

From source file:net.pms.util.GenericIcons.java

/**
 * Add the format(container) name of the media to the generic icon image.
 *
 * @param image BufferdImage to be the label added
 * @param label the media container name to be added as a label
 * @param renderer the renderer configuration
 *
 * @return the generic icon with the container label added and scaled in accordance with renderer setting
 *//*from ww  w .ja  va 2  s  .  c  om*/
private DLNAThumbnail addFormatLabelToImage(String label, ImageFormat imageFormat, IconType iconType)
        throws IOException {

    BufferedImage image;
    switch (iconType) {
    case AUDIO:
        image = genericAudioIcon;
        break;
    case IMAGE:
        image = genericImageIcon;
        break;
    case VIDEO:
        image = genericVideoIcon;
        break;
    default:
        image = genericUnknownIcon;
    }

    if (image != null) {
        // Make a copy
        ColorModel colorModel = image.getColorModel();
        image = new BufferedImage(colorModel, image.copyData(null), colorModel.isAlphaPremultiplied(), null);
    }

    ByteArrayOutputStream out = null;

    if (label != null && image != null) {
        out = new ByteArrayOutputStream();
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        try {
            int size = 40;
            Font font = new Font(Font.SANS_SERIF, Font.BOLD, size);
            FontMetrics metrics = g.getFontMetrics(font);
            while (size > 7 && metrics.stringWidth(label) > 135) {
                size--;
                font = new Font(Font.SANS_SERIF, Font.BOLD, size);
                metrics = g.getFontMetrics(font);
            }
            // Text center point 127x, 49y - calculate centering coordinates
            int x = 127 - metrics.stringWidth(label) / 2;
            int y = 46 + metrics.getAscent() / 2;
            g.drawImage(image, 0, 0, null);
            g.setColor(Color.WHITE);
            g.setFont(font);
            g.drawString(label, x, y);

            ImageIO.setUseCache(false);
            ImageIOTools.imageIOWrite(image, imageFormat.toString(), out);
        } finally {
            g.dispose();
        }
    }
    return out != null ? DLNAThumbnail.toThumbnail(out.toByteArray(), 0, 0, ScaleType.MAX, imageFormat, false)
            : null;
}

From source file:org.cruk.mga.CreateReport.java

/**
 * Returns the FONT height.//from   w  w  w. j  av  a2 s.  c o m
 *
 * @return
 */
private int getFontHeight() {
    BufferedImage image = new BufferedImage(plotWidth, plotWidth, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    g2.setFont(font);
    int fontHeight = g2.getFontMetrics().getAscent();
    g2.dispose();

    return fontHeight;
}

From source file:de.berlios.statcvs.xml.chart.SymbolicNameAnnotation.java

/**
 * @see org.jfree.chart.annotations.XYAnnotation#draw(java.awt.Graphics2D, org.jfree.chart.plot.XYPlot, java.awt.geom.Rectangle2D, org.jfree.chart.axis.ValueAxis, org.jfree.chart.axis.ValueAxis)
 *//*from   w  w  w  .j  a v  a 2s  .  c  o m*/
public void draw(Graphics2D g2d, XYPlot xyPlot, Rectangle2D dataArea, ValueAxis domainAxis,
        ValueAxis rangeAxis) {
    PlotOrientation orientation = xyPlot.getOrientation();

    // don't draw the annotation if symbolic names date is out of axis' bounds.
    if (domainAxis.getUpperBound() < symbolicName.getDate().getTime()
            || domainAxis.getLowerBound() > symbolicName.getDate().getTime()) {

        return;
    }

    RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(xyPlot.getDomainAxisLocation(), orientation);
    RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(xyPlot.getRangeAxisLocation(), orientation);

    float x = (float) domainAxis.translateValueToJava2D(symbolicName.getDate().getTime(), dataArea, domainEdge);
    float y1 = (float) rangeAxis.translateValueToJava2D(rangeAxis.getUpperBound(), dataArea, rangeEdge);
    float y2 = (float) rangeAxis.translateValueToJava2D(rangeAxis.getLowerBound(), dataArea, rangeEdge);

    g2d.setPaint(linePaint);
    g2d.setStroke(stroke);

    Line2D line = new Line2D.Float(x, y1, x, y2);
    g2d.draw(line);

    float anchorX = x;
    float anchorY = y1 + 2;

    g2d.setFont(font);
    g2d.setPaint(textPaint);

    /*g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, 
                     RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);*/

    RefineryUtilities.drawRotatedString(symbolicName.getName(), g2d, anchorX, anchorY, TextAnchor.BOTTOM_RIGHT,
            TextAnchor.BOTTOM_RIGHT, -Math.PI / 2);
}

From source file:net.sourceforge.processdash.ui.web.reports.RadarPlot.java

/**
 * Draws the label for one radar axis./*from   w  ww  .ja  v  a 2  s  .  com*/
 *
 * @param g2 The graphics device.
 * @param chartArea The area for the radar chart.
 * @param data The data for the plot.
 * @param axis The axis (zero-based index).
 * @param startAngle The starting angle.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D chartArea, String label, int axis, double labelX,
        double labelY) {

    // handle label drawing...
    FontRenderContext frc = g2.getFontRenderContext();
    Rectangle2D labelBounds = this.axisLabelFont.getStringBounds(label, frc);
    LineMetrics lm = this.axisLabelFont.getLineMetrics(label, frc);
    double ascent = lm.getAscent();

    if (labelX == chartArea.getCenterX())
        labelX -= labelBounds.getWidth() / 2;
    else if (labelX < chartArea.getCenterX())
        labelX -= labelBounds.getWidth();
    if (labelY > chartArea.getCenterY())
        labelY += ascent;

    g2.setPaint(this.axisLabelPaint);
    g2.setFont(this.axisLabelFont);
    g2.drawString(label, (float) labelX, (float) labelY);
}

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void clear() {
    Drawable command = new Drawable() {

        @Override//from ww w .  j  a  v a  2 s.co m
        public void draw(Graphics2D g2, TurtleState turtleState) {
            try {
                g2.setColor(Color.white);
                g2.fillRect(0, 0, turtleState.width > 0 ? (int) turtleState.width : getWidth(),
                        turtleState.height > 0 ? (int) turtleState.height : getHeight());
                turtleState.penColor = Color.black;
                g2.setColor(turtleState.penColor);

                turtleState.font = new Font(null, 0, 12);

                g2.setFont(turtleState.font);
            } catch (Exception ex) {

            }
        }

        @Override
        public void addListener(DrawListener listener) {
        }

        @Override
        public void removeListener(DrawListener listener) {
        }

        @Override
        public Drawable cloneDrawable() {
            return this;
        }
    };
    submitCommand(command);
}

From source file:edu.dlnu.liuwenpeng.render.XYBarRenderer.java

/**
 * Draws an item label.  This method is provided as an alternative to
 * {@link #drawItemLabel(Graphics2D, PlotOrientation, XYDataset, int, int, 
 * double, double, boolean)} so that the bar can be used to calculate the 
 * label anchor point. /*  w w  w.j  a  va2  s .com*/
 * 
 * @param g2  the graphics device.
 * @param dataset  the dataset.
 * @param series  the series index.
 * @param item  the item index.
 * @param plot  the plot.
 * @param generator  the label generator (<code>null</code> permitted, in 
 *         which case the method does nothing, just returns).
 * @param bar  the bar.
 * @param negative  a flag indicating a negative value.
 */
protected void drawItemLabel(Graphics2D g2, XYDataset dataset, int series, int item, XYPlot plot,
        XYItemLabelGenerator generator, Rectangle2D bar, boolean negative) {

    if (generator == null) {
        return; // nothing to do
    }
    String label = generator.generateLabel(dataset, series, item);
    if (label == null) {
        return; // nothing to do   
    }

    Font labelFont = getItemLabelFont(series, item);
    g2.setFont(labelFont);
    Paint paint = getItemLabelPaint(series, item);
    g2.setPaint(paint);

    // find out where to place the label...
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(series, item);
    } else {
        position = getNegativeItemLabelPosition(series, item);
    }

    // work out the label anchor point...
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar, plot.getOrientation());

    if (isInternalAnchor(position.getItemLabelAnchor())) {
        Shape bounds = TextUtilities.calculateRotatedStringBounds(label, g2, (float) anchorPoint.getX(),
                (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(),
                position.getRotationAnchor());

        if (bounds != null) {
            if (!bar.contains(bounds.getBounds2D())) {
                if (!negative) {
                    position = getPositiveItemLabelPositionFallback();
                } else {
                    position = getNegativeItemLabelPositionFallback();
                }
                if (position != null) {
                    anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar,
                            plot.getOrientation());
                }
            }
        }

    }

    if (position != null) {
        TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(),
                position.getTextAnchor(), position.getAngle(), position.getRotationAnchor());
    }
}