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:ucar.unidata.idv.control.chart.WayPoint.java

/**
 * Draws the annotation.// www  . ja  v  a 2  s  .c  o  m
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param rendererIndex  the renderer index.
 * @param info  an optional info object that will be populated with
 *              entity information.
 */
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {
    super.setGraphicsState(g2);
    if (!getPlotWrapper().okToDraw(this)) {
        return;
    }

    g2.setStroke(new BasicStroke());
    if (false && getSelected()) {
        g2.setColor(COLOR_SELECTED);
    } else {
        g2.setColor(getColor());
    }
    x = getXFromValue(dataArea, domainAxis);

    int width2 = (int) (ANNOTATION_WIDTH / 2);
    int bottom = (int) (dataArea.getY() + dataArea.getHeight());
    y = bottom;
    int[] xs = { x - width2, x + width2, x, x - width2 };
    int[] ys = { bottom - ANNOTATION_WIDTH, bottom - ANNOTATION_WIDTH, bottom, bottom - ANNOTATION_WIDTH };
    g2.fillPolygon(xs, ys, xs.length);

    if ((getName() != null) && !isForAnimation) {
        FontMetrics fm = g2.getFontMetrics();
        int width = fm.stringWidth(getName());
        int textLeft = x - width / 2;
        g2.drawString(getName(), textLeft, bottom - ANNOTATION_WIDTH - 2);
    }

    if (getSelected()) {
        g2.setColor(COLOR_SELECTED);
        g2.drawPolygon(xs, ys, xs.length);
    }

    if (getPropertyListeners().hasListeners(PROP_WAYPOINTVALUE) || isForAnimation) {
        g2.setColor(Color.gray);
        g2.drawLine(x, y - ANNOTATION_WIDTH, x, (int) dataArea.getY());
    }

    boolean playSound = canPlaySound();

    if (isForAnimation) {
        if (clockImage == null) {
            clockImage = GuiUtils.getImage("/auxdata/ui/icons/clock.gif");
        }
        if (playSound) {
            g2.drawImage(clockImage, x - 8, (int) dataArea.getY() + 1, null);
        } else {
            g2.drawImage(clockImage, x - 8, (int) dataArea.getY() + 1, null);
        }
    }

    if (canPlaySound()) {
        if (noteImage == null) {
            noteImage = GuiUtils.getImage("/auxdata/ui/icons/note.gif");
        }
        if (isForAnimation) {
            g2.drawImage(noteImage, x + 8, (int) dataArea.getY() + 1, null);
        } else {
            g2.drawImage(noteImage, x, (int) dataArea.getY() + 1, null);
        }
    }

    if (minutesSpan > 0.0) {
        int left = (int) domainAxis.valueToJava2D(domainValue - (minutesSpan * 60000) / 2, dataArea,
                RectangleEdge.BOTTOM);
        int right = (int) domainAxis.valueToJava2D(domainValue + (minutesSpan * 60000) / 2, dataArea,
                RectangleEdge.BOTTOM);
        g2.setPaint(Color.black);
        g2.setStroke(new BasicStroke(2.0f));
        g2.drawLine(left, y, right, y);
    }

}

From source file:savant.view.tracks.BAMTrackRenderer.java

/**
 * Draw the legend for bases, but also the entries for insertions and
 * deletions./*ww  w.  ja  v a 2 s  .co m*/
 */
private void drawBaseLegendExtended(Graphics2D g2, int x, int y, ColourKey... keys) {
    drawBaseLegend(g2, x, y, keys);

    y += LEGEND_LINE_HEIGHT;
    g2.setColor(Color.BLACK);
    g2.fillRect(x, y - SWATCH_SIZE.height + 2, SWATCH_SIZE.width, SWATCH_SIZE.height);
    g2.setColor(Color.BLACK);
    g2.drawString("Deletion", x + SWATCH_SIZE.width + 3, y);
    x += 66;
    Shape s = drawInsertion(g2, x, y - SWATCH_SIZE.height + 2, 12.0, SWATCH_SIZE.height);
    g2.setColor(Color.BLACK);
    g2.setStroke(new BasicStroke(0.25f));
    g2.draw(s);
    g2.drawString("Insertion", x + 12, y);
}

From source file:net.sourceforge.processdash.ui.lib.chart.StandardDiscItemRenderer.java

protected void drawDiscLabel(Graphics2D g2, Ellipse2D shape, Paint labelPaint, Font labelFont, String label) {
    g2.setFont(labelFont);//from w w w.  j  av  a2 s  . com
    g2.setPaint(labelPaint);
    FontMetrics m = g2.getFontMetrics();
    int height = m.getAscent();
    double halfHeight = height / 2.0;

    double radius = shape.getWidth() / 2;
    double availableRadius = radius - getLabelPadding();
    double halfWidth = Math.sqrt(availableRadius * availableRadius - halfHeight * halfHeight);

    int width = (int) Math.floor(halfWidth * 2 + 0.99);

    Rectangle viewR = new Rectangle(width, height);
    Rectangle iconR = new Rectangle();
    Rectangle textR = new Rectangle();
    String text = SwingUtilities.layoutCompoundLabel(m, label, null, SwingConstants.CENTER,
            SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.TRAILING, viewR, iconR, textR, 0);
    if (text.equals(label) || text.length() >= 3 + minLabelChars) {
        double x = shape.getCenterX() - halfWidth + textR.x;
        double y = shape.getCenterY() + halfHeight + textR.y;
        g2.drawString(text, (float) x, (float) y);
    }
}

From source file:org.executequery.gui.erd.ErdTable.java

protected void drawTable(Graphics2D g, int offsetX, int offsetY) {

    if (parent == null) {

        return;//ww  w.j av  a2s  .  com
    }

    Font tableNameFont = parent.getTableNameFont();
    Font columnNameFont = parent.getColumnNameFont();

    // set the table value background
    g.setColor(TITLE_BAR_BG_COLOR);
    g.fillRect(offsetX, offsetY, FINAL_WIDTH - 1, TITLE_BAR_HEIGHT);

    // set the table value
    FontMetrics fm = g.getFontMetrics(tableNameFont);
    int lineHeight = fm.getHeight();
    int titleXPosn = (FINAL_WIDTH / 2) - (fm.stringWidth(tableName) / 2) + offsetX;

    g.setColor(Color.BLACK);
    g.setFont(tableNameFont);
    g.drawString(tableName, titleXPosn, lineHeight + offsetY);

    // draw the line separator
    lineHeight = TITLE_BAR_HEIGHT + offsetY - 1;
    g.drawLine(offsetX, lineHeight, offsetX + FINAL_WIDTH - 1, lineHeight);

    // fill the white background
    g.setColor(tableBackground);
    g.fillRect(offsetX, TITLE_BAR_HEIGHT + offsetY, FINAL_WIDTH - 1, FINAL_HEIGHT - TITLE_BAR_HEIGHT - 1);

    // add the column names
    fm = g.getFontMetrics(columnNameFont);
    int heightPlusSep = 1 + TITLE_BAR_HEIGHT + offsetY;
    int leftMargin = 5 + offsetX;

    lineHeight = fm.getHeight();
    g.setColor(Color.BLACK);
    g.setFont(columnNameFont);

    int drawCount = 0;
    String value = null;
    if (ArrayUtils.isNotEmpty(columns)) {

        for (int i = 0; i < columns.length; i++) {
            ColumnData column = columns[i];
            if (displayReferencedKeysOnly && !column.isKey()) {
                continue;
            }

            int y = (((drawCount++) + 1) * lineHeight) + heightPlusSep;
            int x = leftMargin;

            // draw the column value string
            value = column.getColumnName();
            g.drawString(value, x, y);

            // draw the data type and size string
            x = leftMargin + dataTypeOffset;
            value = column.getFormattedDataType();
            g.drawString(value, x, y);

            // draw the key label
            if (column.isKey()) {

                if (column.isPrimaryKey() && column.isForeignKey()) {

                    value = PRIMARY + FOREIGN;

                } else if (column.isPrimaryKey()) {

                    value = PRIMARY;

                } else if (column.isForeignKey()) {

                    value = FOREIGN;
                }

                x = leftMargin + dataTypeOffset + keyLabelOffset;
                g.drawString(value, x, y);
            }

        }

    }

    // draw the rectangle border
    double scale = g.getTransform().getScaleX();

    if (selected && scale != ErdPrintable.PRINT_SCALE) {
        g.setStroke(focusBorderStroke);
        g.setColor(Color.BLUE);
    } else {
        g.setColor(Color.BLACK);
    }

    g.drawRect(offsetX, offsetY, FINAL_WIDTH - 1, FINAL_HEIGHT - 1);
    //    g.setColor(Color.DARK_GRAY);
    //    g.draw3DRect(offsetX, offsetY, FINAL_WIDTH - 2, FINAL_HEIGHT - 2, true);
}

From source file:coolmap.canvas.datarenderer.renderer.impl.NumberToColor.java

private void updateGradient() {
    //        System.out.println("Gradient updated..");
    _gradient.reset();/*w w  w .j  av  a  2  s  .  com*/
    for (int i = 0; i < editor.getNumPoints(); i++) {
        Color c = editor.getColorAt(i);
        float p = editor.getColorPositionAt(i);

        if (c == null || p < 0 || p > 1) {
            continue;
        }

        _gradient.addColor(c, p);
    }

    _gradientColors = _gradient.generateGradient(CImageGradient.InterType.Linear);

    int width = DEFAULT_LEGEND_WIDTH;
    int height = DEFAULT_LEGENT_HEIGHT;
    legend = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
    Graphics2D g = (Graphics2D) legend.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    LinearGradientPaint paint = editor.getLinearGradientPaint(0, 0, width, 0);

    g.setPaint(paint);
    g.fillRoundRect(0, 0, width, height - 12, 5, 5);

    g.setColor(UI.colorBlack2);
    g.setFont(UI.fontMono.deriveFont(10f));
    DecimalFormat format = new DecimalFormat("#.##");
    g.drawString(format.format(_minValue), 2, 23);

    String maxString = format.format(_maxValue);
    int swidth = g.getFontMetrics().stringWidth(maxString);
    g.drawString(maxString, width - 2 - swidth, 23);
    g.dispose();

    //        System.out.println("===Gradient updated===" + _gradientColors + " " + this);
}

From source file:org.n52.v3d.terrainserver.povraywts.WebTerrainServlet.java

private void addHints(BufferedImage pImage, VgElevationGrid pTerrain, double pDistance, double pYaw,
        double pExaggeration) {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    DecimalFormat df = new DecimalFormat("0.0", dfs);

    String deltaX = df.format(pTerrain.getGeometry().envelope().getExtentX() / 1000.);
    String deltaY = df.format(pTerrain.getGeometry().envelope().getExtentY() / 1000.);

    String hint = "DIST: " + df.format(pDistance) + ", EXAGG: " + pExaggeration + ", YAW: " + pYaw + ", BBOX: "
            + deltaX + " x " + deltaY + ", DZ: " + df.format(pTerrain.elevationDifference());

    Graphics2D g = pImage.createGraphics();
    g.drawImage(pImage, 0, 0, null);//w ww .j  a va2 s. co  m
    g.setColor(new java.awt.Color(mCopyrightTextColor.getRed(), mCopyrightTextColor.getGreen(),
            mCopyrightTextColor.getBlue()));
    Font font = new Font(mCopyrightTextFont, Font.BOLD /* Style als int, siehe ggf. API-Dok.*/,
            mCopyrightTextSize);
    g.setFont(font);
    g.drawString(hint, 5, mCopyrightTextSize + 5);
    g.dispose();
}

From source file:coolmap.canvas.datarenderer.renderer.impl.NumberToBoxPlot.java

private void updateLegend() {

    int width = DEFAULT_LEGEND_WIDTH;
    int height = DEFAULT_LEGENT_HEIGHT;
    legend = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
    Graphics2D g = (Graphics2D) legend.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setPaint(UI.colorBlack2);/*w  ww .  j a  v  a  2  s.  c  om*/
    g.fillRoundRect(0, 0, width, height - 12, 5, 5);

    g.setColor(barColorBelow);
    int boxNum = 10;
    g.setStroke(UI.stroke1_5);

    double value;
    for (int i = 0; i < boxNum; i++) {
        value = _minValue + (_maxValue - _minValue) / boxNum * i;

        if (value > disectBound) {
            g.setColor(barColorNormal);
        }

        int h = (height - 12) / boxNum * i;
        g.drawLine(i * width / boxNum, height - 12 - h, (i + 1) * width / boxNum, height - 12 - h);

    }

    g.setColor(Color.BLACK);
    g.setFont(UI.fontMono.deriveFont(10f));
    DecimalFormat format = new DecimalFormat("#.##");
    g.drawString(format.format(_minValue), 2, 23);

    g.setColor(Color.BLACK);
    String maxString = format.format(_maxValue);
    int swidth = g.getFontMetrics().stringWidth(maxString);
    g.drawString(maxString, width - 2 - swidth, 23);
    g.dispose();
}

From source file:com.piketec.jenkins.plugins.tpt.publisher.PieChart.java

private void drawLegendLine(Graphics2D g2, int verticalOffset, double horizontalNumberOffset, Color col,
        String txt, String numberText, boolean textIsPlural, boolean withSubSegment, String subSegmentText,
        String subNumberText, boolean subTextIsPlural) {
    int left = 620;
    // col == null --> total --> kein Rechteck
    if (col != null) {
        g2.drawImage(keyShadow.getImage(), left, 30 + verticalOffset, keyShadow.getImageObserver());
        g2.setColor(col);//w  w  w  .j  a va 2s  .  c o m
        g2.fillRect(left + 13, 37 + verticalOffset, 45, 45);
        if (withSubSegment) {
            Polygon p = new Polygon(new int[] { left + 13 + 45, left + 13 + 45, left + 13 },
                    new int[] { verticalOffset + 37, verticalOffset + 37 + 45, verticalOffset + 37 + 45 }, 3);
            g2.setColor(col.darker());
            g2.fillPolygon(p);
        }
    }
    g2.setColor(Color.BLACK);
    StringBuffer sb = new StringBuffer(numberText);
    sb.append("  ").append(plural(textIsPlural, txt));
    if (withSubSegment) {
        sb.append(" with ");
        sb.append(subNumberText);
        sb.append(" ");
        sb.append(plural(subTextIsPlural, subSegmentText));
    }
    g2.drawString(sb.toString(), (int) (left + 80 + horizontalNumberOffset), 30 + 41 + verticalOffset);

}

From source file:savant.view.swing.Ruler.java

/**
 * Render the background of this graphpane
 * @param g The graphics object to use/*w w w .ja  va2 s .  co  m*/
 */
private void renderBackground(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    try {

        Image image = javax.imageio.ImageIO
                .read(getClass().getResource("/savant/images/bar_selected_glossy.png"));
        Composite originalComposite = ((Graphics2D) g).getComposite();
        ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.85F));
        g.drawImage(image, -getWidth(), 0, getWidth() * 3, getHeight(), this);
        ((Graphics2D) g).setComposite(originalComposite);
    } catch (Exception e) {
        LOG.error("Error drawing image background");
    }

    Range r = locationController.getRange();

    // At early points in the GUI initialisation, the range has not yet been set.
    if (r == null) {
        return;
    }

    int[] tickPositions = MiscUtils.getTickPositions(r);
    int separation = tickPositions.length > 1 ? tickPositions[1] - tickPositions[0] : 0;
    int xEnd = Integer.MIN_VALUE;
    FontMetrics fm = g2.getFontMetrics();

    for (int p : tickPositions) {

        int x = MiscUtils.transformPositionToPixel(p, getWidth(), r);
        if (x > xEnd + 10) {
            g2.setColor(new Color(50, 50, 50, 50)); //BrowserDefaults.colorAxisGrid);
            g2.drawLine(x, 0, x, getHeight());

            String numStr = MiscUtils.posToShortStringWithSeparation(p, separation);
            g2.setColor(Color.black);
            g2.drawString(numStr, x + 3, getHeight() / 2 + 3);
            xEnd = x + fm.stringWidth(numStr) + 3;
        }
    }

    if (r.getLength() >= locationController.getRangeStart()) {
        try {
            Image image_left_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_left_bordered.png"));
            int pos = getLeftCapPos();
            g.drawImage(image_left_cap, pos, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, -getWidth(), getHeight());
        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }

    if (r.getLength() >= locationController.getMaxRangeEnd() - locationController.getRangeEnd()) {
        try {
            Image image_right_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_right_bordered.png"));
            int pos = MiscUtils.transformPositionToPixel(locationController.getMaxRangeEnd(), getWidth(),
                    locationController.getRange());
            g.drawImage(image_right_cap, pos - CAP_WIDTH, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, this.getWidth(), this.getHeight());

        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }
}

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphNode.java

/**
 * Draw a GraphNode as a rectangle with a name
 *
 * @param g   The Java2D Graphics/*from   w  w  w  .  j  a va 2 s  .c o  m*/
 * @param col The color to draw
 */
public void drawNode(final Graphics2D g, final Color col) {
    final int x = displayPosition.x;
    final int y = displayPosition.y;

    g.setFont(g.getFont().deriveFont(Font.BOLD, 11));
    final FontMetrics metrics = g.getFontMetrics();
    final String name = node.getId();
    final Rectangle2D rect = metrics.getStringBounds(name, g);
    final int stringWidth = (int) rect.getWidth();
    setSize(Math.max(stringWidth, 50) + 10, 25);

    int step = 4;
    int alpha = 96;
    for (int i = 0; i < step; ++i) {
        g.setColor(new Color(0, 0, 0, alpha - (32 * i)));
        g.drawLine(x + i + 1, y + nodeHeight + i, x + nodeWidth + i - 1, y + nodeHeight + i);
        g.drawLine(x + nodeWidth + i, y + i, x + nodeWidth + i, y + nodeHeight + i);
    }

    Shape clipShape = new Rectangle(x, y, nodeWidth, nodeHeight);

    g.setComposite(AlphaComposite.SrcAtop);
    g.setPaint(new GradientPaint(x, y, col, x + nodeWidth, y + nodeHeight, col.darker()));
    g.fill(clipShape);

    g.setColor(Color.blue);
    g.draw3DRect(x, y, nodeWidth - 1, nodeHeight - 1, true);

    g.setColor(Color.BLACK);
    g.drawString(name, x + (nodeWidth - stringWidth) / 2, y + 15);
}