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:savant.view.swing.GraphPane.java

private void drawMessageHelper(Graphics2D g2, String message, Font font, int w, int h, int offset) {
    g2.setFont(font);//from   w  w  w  .j  a  v  a  2s.c o m
    FontMetrics metrics = g2.getFontMetrics();

    Rectangle2D stringBounds = font.getStringBounds(message, g2.getFontRenderContext());

    int preferredWidth = (int) stringBounds.getWidth() + metrics.getHeight();
    int preferredHeight = (int) stringBounds.getHeight() + metrics.getHeight();

    w = Math.min(preferredWidth, w);
    h = Math.min(preferredHeight, h);

    int x = (getWidth() - (int) stringBounds.getWidth()) / 2;
    int y = (getHeight() / 2) + ((metrics.getAscent() - metrics.getDescent()) / 2) + offset;

    g2.drawString(message, x, y);
}

From source file:nl.b3p.kaartenbalie.core.server.b3pLayering.ConfigLayer.java

protected void drawTitledMessageBox(Graphics2D g2d, String title, String message, int x, int y, int w, int h) {
    /* Do some calculations and init variables. */
    g2d.setFont(KBConfiguration.OHD_messageBoxFont);
    FontMetrics fm = g2d.getFontMetrics();
    int labelHeight = KBConfiguration.OHD_messageBoxFont.getSize() + (KBConfiguration.OHD_padding * 2);
    int angling = labelHeight;
    Rectangle2D testRectangle = fm.getStringBounds(title, g2d);
    int labelWidth = (int) testRectangle.getWidth();

    if (w < labelWidth + (2 * angling)) {
        w = labelWidth + (2 * angling);/*w w  w. j  a v a  2 s  . c o m*/
    }
    y += labelHeight;
    /* Now draw the box...    */
    drawMessageBox(g2d, message, x, y, w, h);

    /* Draw the label background */
    g2d.setColor(KBConfiguration.OHD_labelBoxColor);
    GeneralPath label = new GeneralPath();
    label.moveTo(x, y);
    label.lineTo(x + angling, y - labelHeight);
    label.lineTo(x + angling + labelWidth, y - labelHeight);
    label.lineTo(x + (angling * 2) + labelWidth, y);
    label.closePath();
    g2d.fill(label);

    /* Draw the label Lines..  */
    g2d.setColor(KBConfiguration.OHD_borderBoxTopLeft);
    g2d.drawLine(x, y, x + angling, y - labelHeight);
    g2d.drawLine(x + angling, y - labelHeight, x + angling + labelWidth, y - labelHeight);
    g2d.setColor(KBConfiguration.OHD_borderBoxBottomRight);
    g2d.drawLine(x + angling + labelWidth, y - labelHeight, x + (angling * 2) + labelWidth, y);
    g2d.setColor(KBConfiguration.OHD_borderBoxBackground);
    g2d.drawLine(x + (angling * 2) + labelWidth, y, x, y);
    /*Then add the title... */
    g2d.setColor(KBConfiguration.OHD_labelFontBoxColor);
    g2d.drawString(title, x + angling, y - KBConfiguration.OHD_padding);

}

From source file:org.n52.oxf.render.sos.TimeSeriesMapChartRenderer.java

/**
 * @param observationCollection// w  ww.  j ava2s. c o m
 * @param screenW
 * @param screenH
 * @param bbox
 * @param selectedFeatures
 *        the Features of Interest for which a chart shall be renderered.
 */
public StaticVisualization renderLayer(OXFFeatureCollection observationCollection, ParameterContainer paramCon,
        int screenW, int screenH, IBoundingBox bbox, Set<OXFFeature> selectedFeatures) {
    if (selectedFeaturesCache == null) {
        selectedFeaturesCache = selectedFeatures;
    }

    // before starting to render --> run garbageCollection
    Runtime.getRuntime().gc();
    LOGGER.info("Garbage Collection done.");
    // --

    String[] observedProperties;
    // which observedProperty has been used?:
    ParameterShell observedPropertyPS = paramCon.getParameterShellWithServiceSidedName("observedProperty");
    if (observedPropertyPS.hasMultipleSpecifiedValues()) {
        observedProperties = observedPropertyPS.getSpecifiedTypedValueArray(String[].class);
    } else if (observedPropertyPS.hasSingleSpecifiedValue()) {
        observedProperties = new String[] { (String) observedPropertyPS.getSpecifiedValue() };
    } else {
        throw new IllegalArgumentException("no observedProperties found.");
    }

    // find tuples:
    if (obsValues4FOI == null) {
        obsValues4FOI = new ObservationSeriesCollection(observationCollection, selectedFeaturesCache,
                observedProperties, true);
    }

    ContextBoundingBox contextBBox = new ContextBoundingBox(bbox);

    BufferedImage image = new BufferedImage(screenW, screenH, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();

    // draw white background:
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, screenW, screenH);

    g.setColor(Color.BLACK);

    for (OXFFeature chartFeature : selectedFeaturesCache) {

        //
        // CACHING: create Plot for each "chart feature" and add it to the cache:
        //
        if (!chartCache.containsKey(chartFeature)) {
            Map<ITimePosition, ObservedValueTuple> timeMap = obsValues4FOI.getAllTuples(chartFeature);

            // draw a chart if there are tuples for the chartFeature available:
            if (timeMap != null) {
                XYPlot chart = drawChart4FOI(chartFeature.getID(), timeMap);
                chartCache.put(chartFeature, chart);
            }
        }

        //
        // draw the plots (which are in the cache):
        //
        Point pRealWorld = (Point) chartFeature.getGeometry();

        java.awt.Point pScreen = ContextBoundingBox.realworld2Screen(contextBBox.getActualBBox(), screenW,
                screenH, new Point2D.Double(pRealWorld.getCoordinate().x, pRealWorld.getCoordinate().y));
        XYPlot cachedPlot = (XYPlot) chartCache.get(chartFeature);

        // if there is a plot in the cache for the chartFeature -> draw it:
        if (cachedPlot != null) {
            cachedPlot.getRangeAxis().setRange((Double) obsValues4FOI.getMinimum(0),
                    (Double) obsValues4FOI.getMaximum(0));

            cachedPlot.draw(g,
                    new Rectangle2D.Float(pScreen.x + X_SHIFT, pScreen.y + Y_SHIFT, CHART_WIDTH, CHART_HEIGHT),
                    null, null, null);
        } else {
            g.drawString("No data available", pScreen.x + X_SHIFT, pScreen.y + Y_SHIFT);
        }

        // draw point of feature:
        g.fillOval(pScreen.x - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                pScreen.y - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                FeatureGeometryRenderer.DOT_SIZE_POINT, FeatureGeometryRenderer.DOT_SIZE_POINT);

    }

    return new StaticVisualization(image);
}

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 {//from   w ww  .j av a  2s. 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:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] generateNoDataChart(int width, int height) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();

    g2d.setBackground(parseColor(statsManager.getChartBackgroundColor()));
    g2d.clearRect(0, 0, width - 1, height - 1);
    g2d.setColor(parseColor("#cccccc"));
    g2d.drawRect(0, 0, width - 1, height - 1);
    Font f = new Font("SansSerif", Font.PLAIN, 12);
    g2d.setFont(f);/*  w ww .  j ava 2  s .c  o  m*/
    FontMetrics fm = g2d.getFontMetrics(f);
    String noData = msgs.getString("no_data");
    int noDataWidth = fm.stringWidth(noData);
    int noDataHeight = fm.getHeight();
    g2d.setColor(parseColor("#555555"));
    g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:lucee.runtime.img.Image.java

public void drawString(String text, int x, int y, Struct attr) throws PageException {

    if (attr != null && attr.size() > 0) {

        // font/*from   ww w. jav  a2 s  .c o  m*/
        String font = StringUtil.toLowerCase(Caster.toString(attr.get("font", ""))).trim();
        if (!StringUtil.isEmpty(font)) {
            font = FontUtil.getFont(font).getFontName();
        } else
            font = "Serif";

        // alpha
        //float alpha=Caster.toFloatValue(attr.get("alpha",null),1F);

        // size
        int size = Caster.toIntValue(attr.get("size", Constants.INTEGER_10));

        // style
        int style = Font.PLAIN;
        String strStyle = StringUtil.toLowerCase(Caster.toString(attr.get("style", "")));
        strStyle = StringUtil.removeWhiteSpace(strStyle);
        if (!StringUtil.isEmpty(strStyle)) {
            if ("plain".equals(strStyle))
                style = Font.PLAIN;
            else if ("bold".equals(strStyle))
                style = Font.BOLD;
            else if ("italic".equals(strStyle))
                style = Font.ITALIC;
            else if ("bolditalic".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else if ("bold,italic".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else if ("italicbold".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else if ("italic,bold".equals(strStyle))
                style = Font.BOLD + Font.ITALIC;
            else
                throw new ExpressionException("key style of argument attributeCollection has an invalid value ["
                        + strStyle + "], valid values are [plain,bold,italic,bolditalic]");
        }

        // strikethrough
        boolean strikethrough = Caster.toBooleanValue(attr.get("strikethrough", Boolean.FALSE));

        // underline
        boolean underline = Caster.toBooleanValue(attr.get("underline", Boolean.FALSE));

        AttributedString as = new AttributedString(text);
        as.addAttribute(TextAttribute.FONT, new Font(font, style, size));
        if (strikethrough)
            as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        if (underline)
            as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        Graphics2D g = getGraphics();
        //if(alpha!=1D) setAlpha(g,alpha);

        g.drawString(as.getIterator(), x, y);
    } else
        getGraphics().drawString(text, x, y);

}

From source file:peakml.util.jfreechart.FastSpectrumPlot.java

@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {/*from w  w w .ja  v  a2s  .  co  m*/
    // add the plot area to the info (used amongst other by the axis for zooming)
    if (info != null)
        info.setPlotArea(area);

    // add the insets (if any)
    RectangleInsets insets = getInsets();
    insets.trim(area);

    // draw the axis and add the dataArea to the info (used amongst other by the axis for zooming)
    AxisSpace space = new AxisSpace();
    space = xaxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space);
    space = yaxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space);

    Rectangle2D dataArea = space.shrink(area, null);
    if (info != null)
        info.setDataArea(dataArea);

    // flood fill the whole area with the background color
    drawBackground(g2, dataArea);

    // draw the axis
    xaxis.draw(g2, dataArea.getMaxY(), area, dataArea, RectangleEdge.BOTTOM, info);
    yaxis.draw(g2, dataArea.getMinX(), area, dataArea, RectangleEdge.LEFT, info);

    // sanity check
    if (dataseries.size() == 0)
        return;

    // clip the draw area
    Shape originalclip = g2.getClip();
    g2.clip(dataArea);

    // draw all the values
    for (Data data : dataseries) {
        int xpos = (int) xaxis.valueToJava2D(data.mass, dataArea, RectangleEdge.BOTTOM);
        int ypos = (int) yaxis.valueToJava2D(data.intensity, dataArea, RectangleEdge.LEFT);
        g2.drawLine(xpos, (int) yaxis.valueToJava2D(0, dataArea, RectangleEdge.LEFT), xpos, ypos);

        // draw the label
        if (data.description != null && data.description.length() != 0) {
            g2.setColor(Color.RED);
            g2.drawLine(xpos + 2, ypos - 2, xpos + 15, ypos - 15);
            g2.setColor(Color.BLACK);
            g2.drawString(data.description, xpos + 17, ypos - 17);
        }
    }

    // reset
    g2.setClip(originalclip);
}

From source file:org.gumtree.vis.awt.time.TimePlotPanel.java

@Override
protected void drawToolTipFollower(Graphics2D g2, int x, int y) {
    Rectangle2D dataArea = getScreenDataArea();
    if (((int) dataArea.getMinX() <= x) && (x <= (int) dataArea.getMaxX()) && ((int) dataArea.getMinY() <= y)
            && (y <= (int) dataArea.getMaxY())) {
        Date date = new Date((long) getChartX());
        String text = "";
        SimpleDateFormat format = new SimpleDateFormat("EEE d MMM HH:mm:ss");
        StringBuffer buffer = new StringBuffer();
        format.format(date, buffer, new FieldPosition(0));
        text = buffer.toString();//  w w w .j av a 2  s . com
        text = "(" + text + String.format(", %.2f)", getChartY());
        int xLoc = x + 10;
        int yLoc = y + 20;
        double width = text.length() * 5.5;
        double height = 15;
        if (xLoc + width > dataArea.getMaxX()) {
            xLoc = (int) (x - width);
        }
        if (yLoc + height > dataArea.getMaxY()) {
            yLoc = (int) (y - height);
        }

        Rectangle2D toolTipArea = new Rectangle2D.Double(xLoc, yLoc, width, height);

        g2.setColor(Color.white);
        g2.fill(toolTipArea);
        g2.setColor(Color.black);
        g2.drawString(text, xLoc + 3, yLoc + 11);
    }
}

From source file:org.multibit.viewsystem.swing.view.panels.ShowPreferencesPanel.java

private ImageIcon createImageIcon(String text) {
    Font font = new Font("Dialog", Font.PLAIN, LANGUAGE_CODE_IMAGE_HEIGHT - 2 * LANGUAGE_CODE_VERTICAL_INSET);

    BufferedImage bimg = new BufferedImage(LANGUAGE_CODE_IMAGE_WIDTH, LANGUAGE_CODE_IMAGE_HEIGHT,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bimg.createGraphics();

    g2.setColor(Color.WHITE);/* w  w  w  .ja  v  a2  s  . c  o m*/
    g2.setFont(font);
    g2.drawString(text, LANGUAGE_CODE_VERTICAL_INSET + 1,
            LANGUAGE_CODE_IMAGE_HEIGHT - 2 * LANGUAGE_CODE_VERTICAL_INSET);

    return new ImageIcon(bimg);
}

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

/**
 * Draws the labels for each dataset ID, returning the x coordinate for
 * subsequent drawing for each row./*w w  w  .  j  a v  a 2 s .c o  m*/
 *
 * @param g2
 * @param offset
 * @param separation
 * @param multiGenomeAlignmentSummaries
 * @return
 */
private int drawLabels(Graphics2D g2, int offset, int separation,
        Collection<MultiGenomeAlignmentSummary> multiGenomeAlignmentSummaries) {
    int n = multiGenomeAlignmentSummaries.size();
    boolean drawNumbers = false;
    if (n > 1) {
        int i = 0;
        for (MultiGenomeAlignmentSummary multiGenomeAlignmentSummary : multiGenomeAlignmentSummaries) {
            i++;
            String datasetId = multiGenomeAlignmentSummary.getDatasetId();
            String datasetDisplayLabel = datasetDisplayLabels.get(datasetId);
            if (!Integer.toString(i).equals(datasetDisplayLabel)) {
                drawNumbers = true;
                break;
            }
        }
    }
    int x = gapSize;
    int y = offset;
    int maxWidth = 0;
    if (drawNumbers) {
        for (int i = 1; i <= n; i++) {
            String s = Integer.toString(i) + ".";
            g2.drawString(s, x, y);
            maxWidth = Math.max(maxWidth, g2.getFontMetrics().stringWidth(s));
            y += separation;
        }
        x += maxWidth + gapSize / 2;
    }
    y = offset;
    maxWidth = 0;
    for (MultiGenomeAlignmentSummary multiGenomeAlignmentSummary : multiGenomeAlignmentSummaries) {
        String datasetId = multiGenomeAlignmentSummary.getDatasetId();
        String datasetDisplayLabel = datasetDisplayLabels.get(datasetId);
        g2.drawString(datasetDisplayLabel, x, y);
        maxWidth = Math.max(maxWidth, g2.getFontMetrics().stringWidth(datasetDisplayLabel));
        y += separation;
    }
    int acceptableWidth = (int) (0.15 * plotWidth);
    if (maxWidth > acceptableWidth) {
        Composite origComposite = g2.getComposite();
        y = offset - g2.getFontMetrics().getHeight() - separation / 4;
        for (int i = 0; i < n; i++) {
            g2.setColor(Color.WHITE);
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
            g2.fillRect(x + acceptableWidth, y, gapSize, separation);
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
            g2.fillRect(x + acceptableWidth + gapSize, y, plotWidth - x - acceptableWidth - gapSize,
                    separation);
            y += separation;
        }
        maxWidth = acceptableWidth;
        g2.setComposite(origComposite);
    }
    return x + maxWidth + gapSize;
}