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:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private void drawInformationBox(Graphics2D g2, Activities activities, Rectangle2D rect, List<String> params,
        List<String> values, String totalParam, double totalValue, Color background_color, Color border_color) {
    final Font oldFont = g2.getFont();
    final Font paramFont = oldFont;
    final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont);
    final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1);
    final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont);
    final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1);
    final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont);

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

    final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Composite oldComposite = g2.getComposite();
    final Color oldColor = g2.getColor();

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(border_color);//w  w  w .j a v  a2  s .  c o m
    g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15);
    g2.setColor(background_color);
    g2.setComposite(Utils.makeComposite(0.75f));
    g2.fillRoundRect(x, y, width, height, 15, 15);
    g2.setComposite(oldComposite);
    g2.setColor(oldColor);

    final Date date = activities.getDate().getTime();
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy");
    final String dateString = simpleDateFormat.format(date);

    final int padding = 5;

    int yy = y + padding + dateFontMetrics.getAscent();
    g2.setFont(dateFont);
    g2.setColor(COLOR_BLUE);
    g2.drawString(dateString, ((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x, yy);

    int index = 0;
    final int dateInfoHeightMargin = 5;
    final int infoTotalHeightMargin = 5;
    final int paramValueHeightMargin = 0;

    yy += dateFontMetrics.getDescent() + dateInfoHeightMargin
            + Math.max(paramFontMetrics.getAscent(), valueFontMetrics.getAscent());
    for (String param : params) {
        final String value = values.get(index++);
        g2.setColor(Color.BLACK);
        g2.setFont(paramFont);
        g2.drawString(param + ":", padding + x, yy);
        g2.setFont(valueFont);
        g2.drawString(value, width - padding - valueFontMetrics.stringWidth(value) + x, yy);
        // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent()
        yy += paramValueHeightMargin + Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight());
    }

    if (values.size() > 1) {
        yy -= paramValueHeightMargin;
        yy += infoTotalHeightMargin;
        if (totalValue > 0.0) {
            g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR);
        } else if (totalValue < 0.0) {
            g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR);
        }

        g2.setFont(paramFont);
        g2.drawString(totalParam + ":", padding + x, yy);
        g2.setFont(valueFont);
        final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace();
        final String totalValueStr = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace,
                totalValue);
        g2.drawString(totalValueStr, width - padding - valueFontMetrics.stringWidth(totalValueStr) + x, yy);
    }

    g2.setColor(oldColor);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
    g2.setFont(oldFont);
}

From source file:net.rptools.maptool.client.ui.ChatTypingNotification.java

/**
 * This component is only made visible when there are notifications to be displayed. That means the first couple of
 * IF statements in this method are redundant since paintComponent() will not be called unless the component is
 * visible, and it will only be visible when there are notifications...
 *///ww  w. j  a  v a2 s.co  m
@Override
protected void paintComponent(Graphics g) {
    //      System.out.println("Chat panel is painting itself...");
    if (AppPreferences.getTypingNotificationDuration() == 0) {
        return;
    }
    LinkedMap chatTypers = MapTool.getFrame().getChatNotificationTimers().getChatTypers();
    if (chatTypers == null || chatTypers.isEmpty()) {
        return;
    }
    Boolean showBackground = AppPreferences.getChatNotificationShowBackground();

    Graphics2D statsG = (Graphics2D) g.create();

    Font boldFont = AppStyle.labelFont.deriveFont(Font.BOLD);
    Font font = AppStyle.labelFont;
    FontMetrics valueFM = g.getFontMetrics(font);
    FontMetrics keyFM = g.getFontMetrics(boldFont);

    int PADDING7 = 7;
    int PADDING3 = 3;
    int PADDING2 = 2;

    BufferedImage img = AppStyle.panelTexture;
    int rowHeight = Math.max(valueFM.getHeight(), keyFM.getHeight());

    setBorder(null);
    int width = AppStyle.miniMapBorder.getRightMargin() + AppStyle.miniMapBorder.getLeftMargin();
    int height = getHeight() - PADDING2 + AppStyle.miniMapBorder.getTopMargin()
            + AppStyle.miniMapBorder.getBottomMargin();

    statsG.setFont(font);
    SwingUtil.useAntiAliasing(statsG);
    Rectangle bounds = new Rectangle(AppStyle.miniMapBorder.getLeftMargin(),
            height - getHeight() - AppStyle.miniMapBorder.getTopMargin(), getWidth() - width,
            getHeight() - AppStyle.miniMapBorder.getBottomMargin() - AppStyle.miniMapBorder.getTopMargin()
                    + PADDING2);

    int y = bounds.y + rowHeight;
    rowHeight = Math.max(rowHeight, AppStyle.chatImage.getHeight());

    setSize(getWidth(), ((chatTypers.size() * (PADDING3 + rowHeight)) + AppStyle.miniMapBorder.getTopMargin()
            + AppStyle.miniMapBorder.getBottomMargin()));

    if (showBackground) {
        g.drawImage(img, 0, 0, getWidth(), getHeight() + PADDING7, this);
        AppStyle.miniMapBorder.paintAround(statsG, bounds);
    }
    Rectangle rightRow = new Rectangle(AppStyle.miniMapBorder.getLeftMargin() + PADDING7,
            AppStyle.miniMapBorder.getTopMargin() + PADDING7, AppStyle.chatImage.getWidth(),
            AppStyle.chatImage.getHeight());

    Set<?> keySet = chatTypers.keySet();
    @SuppressWarnings("unchecked")
    Set<String> playerTimers = (Set<String>) keySet;
    for (String playerNamer : playerTimers) {
        if (showBackground) {
            statsG.setColor(new Color(249, 241, 230, 140));
            statsG.fillRect(bounds.x + PADDING3, y - keyFM.getAscent(),
                    (bounds.width - PADDING7 / 2) - PADDING3, rowHeight);
            statsG.setColor(new Color(175, 163, 149));
            statsG.drawRect(bounds.x + PADDING3, y - keyFM.getAscent(),
                    (bounds.width - PADDING7 / 2) - PADDING3, rowHeight);
        }
        g.drawImage(AppStyle.chatImage, bounds.x + 5, y - keyFM.getAscent(), (int) rightRow.getWidth(),
                (int) rightRow.getHeight(), this);

        // Values
        statsG.setColor(MapTool.getFrame().getChatTypingLabelColor());
        statsG.setFont(boldFont);
        statsG.drawString(I18N.getText("msg.commandPanel.liveTyping", playerNamer),
                bounds.x + AppStyle.chatImage.getWidth() + PADDING7 * 2, y + 5);

        y += PADDING2 + rowHeight;
    }
    if (showBackground) {
        AppStyle.shadowBorder.paintWithin(statsG, bounds);
    } else {
        setOpaque(false);
    }
}

From source file:org.viafirma.util.QRCodeUtil.java

/**
 * Genera codigo de firma para impresin formado por el texto, el cdigo qr
 * del texto y un cdigo de barras con el cdigo de firma.
 * //  w  w  w  .jav a2 s  . c om
 * @param text
 * @param codFirma
 * @return
 * @throws ExcepcionErrorInterno
 */
public byte[] generate(String text, String url, String textoQR, String codFirma) throws ExcepcionErrorInterno {
    // Comprobamos el tamao del texto. No recomendamos textos de mas de 120
    // caracteres
    if (textoQR.length() > MAX_TEXT_SIZE) {
        log.warn("El tamao del texto '" + text + "' ha excedido el tamao mximo. " + text.length() + ">"
                + MAX_TEXT_SIZE);
        textoQR = textoQR.substring(textoQR.lastIndexOf(" "));
        log.warn("El texto sera recortado: '" + textoQR + "'");
    }

    // Generamos la sufperficie de dibujo
    BufferedImage imagenQR = new BufferedImage(ANCHO_ETIQUETA, ALTO_ETIQUETA, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = imagenQR.createGraphics();
    // El fondo es blanco
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, ANCHO_ETIQUETA, ALTO_ETIQUETA);
    g.setColor(Color.BLACK);
    g.setStroke(new BasicStroke(2f));
    // Pintamos la caja de borde
    g.draw(new java.awt.Rectangle(MARGEN_CAJA, MARGEN_CAJA, ANCHO_ETIQUETA - MARGEN_CAJA * 2,
            ALTO_ETIQUETA - MARGEN_CAJA * 2));
    g.draw(new java.awt.Rectangle(MARGEN_CAJA + 3, MARGEN_CAJA + 3, ANCHO_ETIQUETA - MARGEN_CAJA * 2 - 6,
            ALTO_ETIQUETA - MARGEN_CAJA * 2 - 6));

    // Generamos el cdigo QR
    Qrcode x = new Qrcode();
    x.setQrcodeErrorCorrect('L');
    x.setQrcodeEncodeMode('B'); // Modo Binario
    byte[] d = textoQR.getBytes();
    // Generamos el cdigo QR
    boolean[][] s = x.calQrcode(d);
    for (int i = 0; i < s.length; i++) {
        for (int j = 0; j < s.length; j++) {
            if (s[j][i]) {
                g.fillRect(j * SIZE_QR + MARGEN, i * SIZE_QR + MARGEN, SIZE_QR, SIZE_QR);
            }
        }
    }
    int marjenSeparador = MARGEN + SIZE_QR * s.length + MARGEN_CAJA;
    int marjenTexto = marjenSeparador + MARGEN_CAJA;
    // Linea de separacin entre el QR cdigo y el texto
    g.drawLine(marjenSeparador - 3, MARGEN_CAJA + 3, marjenSeparador - 3, ALTO_ETIQUETA - MARGEN_CAJA - 3);
    g.drawLine(marjenSeparador, MARGEN_CAJA + 3, marjenSeparador, ALTO_ETIQUETA - MARGEN_CAJA - 3);

    // Linea de separacin entre texto y cdigo de barras.
    int marjenCodigoBarras = MARGEN + MAX_ROWS * FONT_SIZE;
    // Pintamos una pequea linea de separacin
    g.drawLine(marjenSeparador, marjenCodigoBarras, ANCHO_ETIQUETA - MARGEN_CAJA - 3, marjenCodigoBarras);
    g.drawLine(marjenSeparador, marjenCodigoBarras - 3, ANCHO_ETIQUETA - MARGEN_CAJA - 3,
            marjenCodigoBarras - 3);

    // Escribimos el texto
    List<String> parrafos = split(text);

    g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE));

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (int i = 0; i < parrafos.size(); i++) {
        String linea = parrafos.get(i);
        // Pintamos la nueva linea de texto
        g.drawString(linea, marjenTexto, MARGEN + 3 + (FONT_SIZE * i + 1));
    }

    g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE - 4));
    // Pintamos el texto final de una sola lnea( Generalmente el MD5 )
    //if(url.length())
    if (!url.equals("")) {
        g.drawString("Custodia del documento: ", marjenTexto, marjenCodigoBarras - 10 * 2);
        g.drawString(url, marjenTexto, marjenCodigoBarras - 6);
    }
    marjenCodigoBarras += MARGEN_CAJA;
    // Generamos el cdigo de barras
    try {
        // int marjenCodigoBarras=MARGEN+MAX_ROWS*FONT_SIZE;
        BarcodeFactory.createCode39(codFirma, true).draw(g, marjenTexto, marjenCodigoBarras);
    } catch (Exception e1) { // TODO
        e1.printStackTrace();
    }
    // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    // RenderingHints.VALUE_ANTIALIAS_OFF);

    // Finalizamos la superficie de dibujo
    g.dispose();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // Generamos la imagen
    try {
        ImageIO.write(imagenQR, "png", out);
        // ImageIO.write(imagenQR, "png", new
        // FileOutputStream("/tmp/imagen.png"));
        out.close();
    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }

    return out.toByteArray();
}

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

protected Image renderFrame(ITimePosition[] sortedTimeArray, int currentTimeIndex, int screenW, int screenH,
        IBoundingBox bbox, Set<OXFFeature> featuresWithCharts, ObservationSeriesCollection tupleFinder) {
    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);/* w w  w .  j  a v  a2 s .com*/
    g.fillRect(0, 0, screenW, screenH);

    g.setColor(Color.BLACK);

    ITimePosition currentTimePos = sortedTimeArray[currentTimeIndex];

    for (OXFFeature chartFeature : featuresWithCharts) {

        //
        // create Plot for each "chart feature" and add it to the cache:
        //
        if (!chartCache.contains(currentTimePos, chartFeature)) {

            // if there is a data tuple for the current time position -> create a new plot
            if (tupleFinder.getTuple(chartFeature, currentTimePos) != null) {
                CategoryPlot plot = drawChart4FOI(chartFeature.getID(), currentTimePos.toString(),
                        tupleFinder.getTuple(chartFeature, currentTimePos));
                chartCache.add(currentTimePos, chartFeature, plot);
            }
        }

        CategoryPlot plot = (CategoryPlot) chartCache.get(currentTimePos, chartFeature);

        // if there wasn't a plot for the current time position go backwards through the sortedTimeArray and take the most recent one:
        int j = currentTimeIndex - 1;
        while (plot == null && j >= 0) {
            plot = (CategoryPlot) chartCache.get(sortedTimeArray[j], chartFeature);
            j--;
        }

        //
        // draw the plots into the image at the georeferenced position of the corresponding chartFeature:
        //
        Point pRealWorld = (Point) chartFeature.getGeometry();

        java.awt.Point pScreen = ContextBoundingBox.realworld2Screen(contextBBox.getActualBBox(), screenW,
                screenH, new Point2D.Double(pRealWorld.getCoordinate().x, pRealWorld.getCoordinate().y));
        // if an appropriate plot was found -> draw it
        if (plot != null) {
            for (int i = 0; i < observedProperties.length; i++) {
                plot.getRangeAxis(i).setRange((Double) tupleFinder.getMinimum(i) - 5,
                        (Double) tupleFinder.getMaximum(i));
                if (i > 0) {
                    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
                }
            }

            plot.draw(g,
                    new Rectangle2D.Float(pScreen.x + X_SHIFT + 10, pScreen.y + Y_SHIFT,
                            CHART_WIDTH + observedProperties.length * CHART_WIDTH_MULTIPLICATOR, CHART_HEIGHT),
                    null, null, null);
        }
        // otherwise draw "no data available"
        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 image;
}

From source file:com.t3.client.ui.ChatTypingNotification.java

/**
 * This component is only made visible when there are notifications to be displayed. That means the first couple of
 * IF statements in this method are redundant since paintComponent() will not be called unless the component is
 * visible, and it will only be visible when there are notifications...
 *//* w ww. j ava2 s. c o  m*/
@Override
protected void paintComponent(Graphics g) {
    //      System.out.println("Chat panel is painting itself...");
    if (AppPreferences.getTypingNotificationDuration() != 0) {
        LinkedMap<String, Long> chatTypers = TabletopTool.getFrame().getChatNotificationTimers()
                .getChatTypers();
        if (chatTypers == null || chatTypers.isEmpty()) {
            return;
        }
        Boolean showBackground = AppPreferences.getChatNotificationShowBackground();

        Graphics2D statsG = (Graphics2D) g.create();

        Font boldFont = AppStyle.labelFont.deriveFont(Font.BOLD);
        Font font = AppStyle.labelFont;
        FontMetrics valueFM = g.getFontMetrics(font);
        FontMetrics keyFM = g.getFontMetrics(boldFont);

        int PADDING7 = 7;
        int PADDING3 = 3;
        int PADDING2 = 2;

        BufferedImage img = AppStyle.panelTexture;
        int rowHeight = Math.max(valueFM.getHeight(), keyFM.getHeight());

        setBorder(null);
        int width = AppStyle.miniMapBorder.getRightMargin() + AppStyle.miniMapBorder.getLeftMargin();
        int height = getHeight() - PADDING2 + AppStyle.miniMapBorder.getTopMargin()
                + AppStyle.miniMapBorder.getBottomMargin();

        statsG.setFont(font);
        SwingUtil.useAntiAliasing(statsG);
        Rectangle bounds = new Rectangle(AppStyle.miniMapBorder.getLeftMargin(),
                height - getHeight() - AppStyle.miniMapBorder.getTopMargin(), getWidth() - width,
                getHeight() - AppStyle.miniMapBorder.getBottomMargin() - AppStyle.miniMapBorder.getTopMargin()
                        + PADDING2);

        int y = bounds.y + rowHeight;
        rowHeight = Math.max(rowHeight, AppStyle.chatImage.getHeight());

        setSize(getWidth(), ((chatTypers.size() * (PADDING3 + rowHeight))
                + AppStyle.miniMapBorder.getTopMargin() + AppStyle.miniMapBorder.getBottomMargin()));

        if (showBackground) {
            g.drawImage(img, 0, 0, getWidth(), getHeight() + PADDING7, this);
            AppStyle.miniMapBorder.paintAround(statsG, bounds);
        }
        Rectangle rightRow = new Rectangle(AppStyle.miniMapBorder.getLeftMargin() + PADDING7,
                AppStyle.miniMapBorder.getTopMargin() + PADDING7, AppStyle.chatImage.getWidth(),
                AppStyle.chatImage.getHeight());

        Set<?> keySet = chatTypers.keySet();
        @SuppressWarnings("unchecked")
        Set<String> playerTimers = (Set<String>) keySet;
        Color c1 = new Color(249, 241, 230, 140);
        Color c2 = new Color(175, 163, 149);
        for (String playerNamer : playerTimers) {
            if (showBackground) {
                statsG.setColor(c1);
                statsG.fillRect(bounds.x + PADDING3, y - keyFM.getAscent(),
                        (bounds.width - PADDING7 / 2) - PADDING3, rowHeight);
                statsG.setColor(c2);
                statsG.drawRect(bounds.x + PADDING3, y - keyFM.getAscent(),
                        (bounds.width - PADDING7 / 2) - PADDING3, rowHeight);
            }
            g.drawImage(AppStyle.chatImage, bounds.x + 5, y - keyFM.getAscent(), (int) rightRow.getWidth(),
                    (int) rightRow.getHeight(), this);

            // Values
            statsG.setColor(TabletopTool.getFrame().getChatTypingLabelColor());
            statsG.setFont(boldFont);
            statsG.drawString(I18N.getText("msg.commandPanel.liveTyping", playerNamer),
                    bounds.x + AppStyle.chatImage.getWidth() + PADDING7 * 2, y + 5);

            y += PADDING2 + rowHeight;
        }
        if (showBackground) {
            AppStyle.shadowBorder.paintWithin(statsG, bounds);
        } else {
            setOpaque(false);
        }
    }
}

From source file:org.squidy.designer.zoom.impl.VisualizationShape.java

@Override
protected void paintShapeZoomedIn(PPaintContext paintContext) {

    Graphics2D g = paintContext.getGraphics();

    PBounds bounds = getBoundsReference();

    //      PBounds cameraBounds = getBoundsReference();// paintContext.getCamera().getFullBoundsReference();
    //      double cameraX = cameraBounds.getX() - 20;
    //      double cameraY = cameraBounds.getY();
    //      double cameraWidth = cameraBounds.getWidth() + 40;
    //      double cameraHeight = cameraBounds.getHeight();

    //      g.setColor(Color.WHITE);
    //      g.fillRect((int) cameraX, (int) cameraY, (int) cameraWidth, (int) cameraHeight);
    ///* ww  w .  j av  a  2  s.  co m*/
    //      g.setColor(Color.BLACK);
    //      g.fillRect((int) cameraX, (int) (cameraY + cameraHeight / 4), (int) cameraWidth, (int) (cameraHeight / 2));

    g.setFont(fontLables);

    // Paint node labels.
    paintNodeLabels(paintContext);

    super.paintShapeZoomedIn(paintContext);

    // Paint headline.
    if (!isShowNavigation()) {
        paintHeadline(paintContext);
    }

    g.setFont(fontSmall);

    // Translate the current graphics position to 1/4 width and 1/4 height
    // of this shape.
    TRANSLATION.setToTranslation((int) (bounds.getWidth() / 4), (int) (bounds.getHeight() / 4));
    paintContext.pushTransform(TRANSLATION);

    // Scale up visualization are because of int constraints to avoid
    // mathematical round failure.
    int maxWidth = (int) ((bounds.getWidth() / 2) * 10);
    int maxHeight = (int) ((bounds.getHeight() / 2) * 10);

    paintContext.pushTransform(SCALE_TRANSFROM);

    PlotContext plotContext = new PlotContext(paintContext, maxWidth, maxHeight, SCALE_TRANSFORM_SCALING,
            sampleTime);

    long currentTime = System.currentTimeMillis();
    for (IDataContainer dataContainer : DATA_QUEUE) {
        if ((currentTime - dataContainer.getTimestamp()) >= sampleTime) {
            DATA_QUEUE.remove(dataContainer);
            continue;
        }

        // Delegates plot of data to visualization.
        visualizations[visualizationIndex].plotData(plotContext, dataContainer);
    }

    // Paints the grid.
    visualizations[visualizationIndex].paintContextual(paintContext, plotContext);

    paintContext.popTransform(SCALE_TRANSFROM);

    // Pop transform translation.
    paintContext.popTransform(TRANSLATION);

    g.setFont(fontFPS);
    g.drawString("FPS: " + currentFPS, (int) (bounds.getWidth() / 2 - 50), (int) (bounds.getHeight() - 100));

    g.setFont(fontHeadline.deriveFont(18f));
    g.setColor(Color.RED);
    g.fillOval((int) (bounds.getWidth() - 115), (int) (bounds.getHeight() / 2 - 20), 10, 10);
    g.setColor(Color.BLACK);
    g.drawString("x-value", (int) (bounds.getWidth() - 100), (int) (bounds.getHeight() / 2 - 10));

    g.setColor(Color.BLUE);
    g.fillOval((int) (bounds.getWidth() - 115), (int) (bounds.getHeight() / 2 + 20), 10, 10);
    g.setColor(Color.BLACK);
    g.drawString("y-value", (int) (bounds.getWidth() - 100), (int) (bounds.getHeight() / 2 + 30));
}

From source file:org.gumtree.vis.plot1d.Plot1DPanel.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())) {
        String text = "";
        if (indexInTooltip) {
            text += "#" + getItemIndex() + ", ";
        }/*from  w ww. j  ava2s .c o m*/
        text += String.format("(%." + mouseFollowerXPrecision + "f, %." + mouseFollowerYPrecision + "f",
                getChartX(), getChartY());
        boolean isErrorEnabled = false;
        XYItemRenderer renderer = getXYPlot().getRenderer();
        if (renderer instanceof XYErrorRenderer) {
            isErrorEnabled = ((XYErrorRenderer) renderer).getDrawYError();
        }
        if (isErrorEnabled) {
            text += String.format(" \u00B1%." + mouseFollowerYPrecision + "f", getChartError());
        }
        text += ")";
        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.lightGray);
        g2.fill(toolTipArea);
        g2.setColor(Color.black);
        g2.drawString(text, xLoc + 3, yLoc + 11);
    }
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private void drawBusyBox(Graphics2D g2, JXLayer<? extends V> layer) {
    final Font oldFont = g2.getFont();
    final Font font = oldFont;
    final FontMetrics fontMetrics = g2.getFontMetrics(font);

    // Not sure why. Draw GIF image on JXLayer, will cause endless setDirty
    // being triggered by system.
    //final Image image = ((ImageIcon)Icons.BUSY).getImage();
    //final int imgWidth = Icons.BUSY.getIconWidth();
    //final int imgHeight = Icons.BUSY.getIconHeight();
    //final int imgMessageWidthMargin = 5;
    final int imgWidth = 0;
    final int imgHeight = 0;
    final int imgMessageWidthMargin = 0;

    final String message = MessagesBundle.getString("info_message_retrieving_latest_stock_price");
    final int maxWidth = imgWidth + imgMessageWidthMargin + fontMetrics.stringWidth(message);
    final int maxHeight = Math.max(imgHeight, fontMetrics.getHeight());

    final int padding = 5;
    final int width = maxWidth + (padding << 1);
    final int height = maxHeight + (padding << 1);
    final int x = (int) this.drawArea.getX() + (((int) this.drawArea.getWidth() - width) >> 1);
    final int y = (int) this.drawArea.getY() + (((int) this.drawArea.getHeight() - height) >> 1);

    final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Composite oldComposite = g2.getComposite();
    final Color oldColor = g2.getColor();

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(COLOR_BORDER);//from   w w  w .  j  a  va 2 s.c o  m
    g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15);
    g2.setColor(COLOR_BACKGROUND);
    g2.setComposite(Utils.makeComposite(0.75f));
    g2.fillRoundRect(x, y, width, height, 15, 15);
    g2.setComposite(oldComposite);
    g2.setColor(oldColor);

    //g2.drawImage(image, x + padding, y + ((height - imgHeight) >> 1), layer.getView());

    g2.setFont(font);
    g2.setColor(COLOR_BLUE);

    int yy = y + ((height - fontMetrics.getHeight()) >> 1) + fontMetrics.getAscent();
    g2.setFont(font);
    g2.setColor(COLOR_BLUE);
    g2.drawString(message, x + padding + imgWidth + imgMessageWidthMargin, yy);
    g2.setColor(oldColor);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
    g2.setFont(oldFont);
}

From source file:org.gumtree.vis.awt.JChartPanel.java

private void drawTextInputBox(Graphics2D g2) {
    if (textInputFlag && textInputPoint != null) {
        //         g2.drawChars("Input Text Here".toCharArray(), 1, 60, (int) textInputPoint.getX(), (int) textInputPoint.getY());
        Color oldColor = g2.getColor();
        g2.setColor(Color.BLACK);
        String inputText = textInputContent == null ? "" : textInputContent;
        FontMetrics fm = g2.getFontMetrics();
        //         int sWidth;
        //         if (textInputCursorIndex == 0 || inputText.length() == 0) {
        //            sWidth = 0;
        //         } else if (textInputCursorIndex < inputText.length()){
        //            sWidth = fm.stringWidth(inputText.substring(0, textInputCursorIndex));
        //         } else {
        //            sWidth = fm.stringWidth(inputText);
        //         }

        String[] lines = inputText.split("\n", 100);
        int cursorY = 0;
        int cursorX = 0;
        int charCount = 0;
        int maxWidth = 0;
        int maxHeight = 0;
        for (int i = 0; i < lines.length; i++) {
            g2.drawString(lines[i], (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3 + i * 15);
            //            charCount += lines[i].length() + 1;
            if (textInputCursorIndex > charCount && textInputCursorIndex < charCount + lines[i].length() + 1) {
                cursorY = i;/*from w w w  .ja  v a  2 s  .c om*/
                cursorX = fm.stringWidth(lines[i].substring(0, textInputCursorIndex - charCount));
            } else if (textInputCursorIndex == charCount + lines[i].length() + 1) {
                cursorY = i + 1;
                cursorX = 0;
            }
            charCount += lines[i].length() + 1;
            int lineWidth = fm.stringWidth(lines[i]);
            if (lineWidth > maxWidth) {
                maxWidth = lineWidth;
            }
        }
        maxHeight = 15 * lines.length;
        //         g2.drawString(inputText, (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3);
        g2.setColor(Color.MAGENTA);
        //         g2.drawString("|", (float) textInputPoint.getX() + 2 + sWidth, (float) textInputPoint.getY() - 3);
        g2.drawLine((int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + (cursorY - 1) * 15,
                (int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + cursorY * 15);
        g2.setColor(Color.BLACK);
        g2.setColor(oldColor);

        //         int boxWidth = fm.stringWidth(inputText) + 10;
        if (maxWidth < 100) {
            maxWidth = 100;
        }
        Rectangle2D inputBox = new Rectangle2D.Double(textInputPoint.getX(), textInputPoint.getY() - 15,
                maxWidth + 8, maxHeight);
        //         ChartMaskingUtilities.drawMaskBoarder(g2, inputBox);
        Color fillColor = new Color(250, 250, 50, 30);
        g2.setPaint(fillColor);
        g2.fill(inputBox);
        g2.setColor(Color.ORANGE);
        g2.drawRect((int) textInputPoint.getX(), (int) textInputPoint.getY() - 15, maxWidth + 8, maxHeight);
    }
    if (textContentMap.size() > 0) {
        Color oldColor = g2.getColor();
        g2.setColor(Color.BLACK);
        Rectangle2D imageArea = getScreenDataArea();
        for (Entry<Rectangle2D, String> entry : textContentMap.entrySet()) {
            Rectangle2D rect = entry.getKey();
            Point2D screenPoint = ChartMaskingUtilities
                    .translateChartPoint(new Point2D.Double(rect.getX(), rect.getY()), imageArea, getChart());
            String text = entry.getValue();
            if (text == null) {
                continue;
            }
            String[] lines = text.split("\n");
            g2.setColor(Color.BLACK);
            for (int i = 0; i < lines.length; i++) {
                g2.drawString(lines[i], (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3 + i * 15);
            }
            if (rect == selectedTextWrapper) {
                FontMetrics fm = g2.getFontMetrics();
                int maxWidth = 0;
                int maxHeight = 0;
                for (int i = 0; i < lines.length; i++) {
                    int lineWidth = fm.stringWidth(lines[i]);
                    if (lineWidth > maxWidth) {
                        maxWidth = lineWidth;
                    }
                }
                maxHeight = 15 * lines.length;
                if (maxWidth < 100) {
                    maxWidth = 100;
                }
                Rectangle2D inputBox = new Rectangle2D.Double(screenPoint.getX(), screenPoint.getY() - 15,
                        maxWidth + 8, maxHeight);
                Color fillColor = new Color(250, 250, 50, 30);
                g2.setPaint(fillColor);
                g2.fill(inputBox);
                g2.setColor(Color.ORANGE);
                g2.drawRect((int) screenPoint.getX(), (int) screenPoint.getY() - 15, maxWidth + 8, maxHeight);

            }
            //            g2.drawString(text == null ? "" : text, (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3);
        }
        g2.setColor(oldColor);
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.graphics.internal.LogicalPageDrawable.java

/**
 * Renders the glyphs stored in the text node.
 *
 * @param renderableText/*from   w  w w  . j  a  v  a2s .  c o m*/
 *          the text node that should be rendered.
 * @param contentX2
 */
protected void drawText(final RenderableText renderableText, final long contentX2) {
    if (renderableText.getLength() == 0) {
        // This text is empty.
        return;
    }

    final long posX = renderableText.getX();
    final long posY = renderableText.getY();

    final Graphics2D g2;
    if (getTextSpec() == null) {
        g2 = (Graphics2D) getGraphics().create();
        final StyleSheet layoutContext = renderableText.getStyleSheet();
        configureGraphics(layoutContext, g2);
        g2.setStroke(LogicalPageDrawable.DEFAULT_STROKE);

        if (RenderUtility.isFontSmooth(layoutContext, metaData)) {
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        } else {
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        }
    } else {
        g2 = getTextSpec().getGraphics();
    }

    // This shifting is necessary to make sure that all text is rendered like in the previous versions.
    // In the earlier versions, we did not really obey to the baselines of the text, we just hoped and prayed.
    // Therefore, all text was printed at the bottom of the text elements. With the introduction of the full
    // font metrics setting, this situation got a little bit better, for the price that text-elements became
    // nearly unpredictable ..
    //
    // The code below may be weird, but at least it is predictable weird.

    final FontMetrics fm = g2.getFontMetrics();
    final Rectangle2D rect = fm.getMaxCharBounds(g2);
    final long awtBaseLine = StrictGeomUtility.toInternalValue(-rect.getY());

    final GlyphList gs = renderableText.getGlyphs();
    if (metaData.isFeatureSupported(OutputProcessorFeature.FAST_FONTRENDERING)
            && isNormalTextSpacing(renderableText)) {
        final int maxLength = renderableText.computeMaximumTextSize(contentX2);
        final String text = gs.getText(renderableText.getOffset(), maxLength, codePointBuffer);
        final float y = (float) StrictGeomUtility.toExternalValue(posY + awtBaseLine);
        g2.drawString(text, (float) StrictGeomUtility.toExternalValue(posX), y);
    } else {
        final ExtendedBaselineInfo baselineInfo = renderableText.getBaselineInfo();
        final int maxPos = renderableText.getOffset() + renderableText.computeMaximumTextSize(contentX2);
        long runningPos = posX;
        final long baseline = baselineInfo.getBaseline(baselineInfo.getDominantBaseline());
        final long baselineDelta = awtBaseLine - baseline;
        final float y = (float) (StrictGeomUtility.toExternalValue(posY + awtBaseLine + baselineDelta));
        for (int i = renderableText.getOffset(); i < maxPos; i++) {
            final Glyph g = gs.getGlyph(i);
            g2.drawString(gs.getGlyphAsString(i, codePointBuffer),
                    (float) StrictGeomUtility.toExternalValue(runningPos), y);
            runningPos += RenderableText.convert(g.getWidth()) + g.getSpacing().getMinimum();
        }
    }
    g2.dispose();
}