Example usage for java.awt Graphics drawString

List of usage examples for java.awt Graphics drawString

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:PaginationExample.java

public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {

    Font font = new Font("Serif", Font.PLAIN, 10);
    FontMetrics metrics = g.getFontMetrics(font);
    int lineHeight = metrics.getHeight();

    if (pageBreaks == null) {
        initTextLines();//from  w  w  w.  ja v a 2 s  .c o  m
        int linesPerPage = (int) (pf.getImageableHeight() / lineHeight);
        int numBreaks = (textLines.length - 1) / linesPerPage;
        pageBreaks = new int[numBreaks];
        for (int b = 0; b < numBreaks; b++) {
            pageBreaks[b] = (b + 1) * linesPerPage;
        }
    }

    if (pageIndex > pageBreaks.length) {
        return NO_SUCH_PAGE;
    }

    /*
     * User (0,0) is typically outside the imageable area, so we must translate
     * by the X and Y values in the PageFormat to avoid clipping Since we are
     * drawing text we
     */
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());

    /*
     * Draw each line that is on this page. Increment 'y' position by lineHeight
     * for each line.
     */
    int y = 0;
    int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex - 1];
    int end = (pageIndex == pageBreaks.length) ? textLines.length : pageBreaks[pageIndex];
    for (int line = start; line < end; line++) {
        y += lineHeight;
        g.drawString(textLines[line], 0, y);
    }

    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
}

From source file:BeanContainer.java

public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Color colorRetainer = g.getColor();

        g.setColor(getBackground());/* w w w.j  a v  a2 s . c  om*/
        g.fillRect(0, 0, getWidth(), getHeight());
        getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight());

        m_calendar.setTime(new Date()); // get current time
        int hrs = m_calendar.get(Calendar.HOUR_OF_DAY);
        int min = m_calendar.get(Calendar.MINUTE);

        g.setColor(getForeground());
        if (m_digital) {
            String time = "" + hrs + ":" + min;
            g.setFont(getFont());
            FontMetrics fm = g.getFontMetrics();
            int y = (getHeight() + fm.getAscent()) / 2;
            int x = (getWidth() - fm.stringWidth(time)) / 2;
            g.drawString(time, x, y);
        } else {
            int x = getWidth() / 2;
            int y = getHeight() / 2;
            int rh = getHeight() / 4;
            int rm = getHeight() / 3;

            double ah = ((double) hrs + min / 60.0) / 6.0 * Math.PI;
            double am = min / 30.0 * Math.PI;

            g.drawLine(x, y, (int) (x + rh * Math.sin(ah)), (int) (y - rh * Math.cos(ah)));
            g.drawLine(x, y, (int) (x + rm * Math.sin(am)), (int) (y - rm * Math.cos(am)));
        }

        g.setColor(colorRetainer);
    }

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

/**
 * Write a blank image so user doesn't see the broken icon.
 *//*from ww w.  jav a2 s .  co  m*/
private void writePlaceholderImage(OutputStream os) throws IOException {
    int placeholderSize = (int) (ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX * 0.75);
    BufferedImage buffer = new BufferedImage(placeholderSize, placeholderSize, BufferedImage.TYPE_INT_RGB);
    Graphics g = buffer.createGraphics();
    g.setColor(Color.lightGray);
    g.fillRect(0, 0, placeholderSize, placeholderSize);
    g.setColor(Color.black);
    g.drawString("Not available", placeholderSize / 4, placeholderSize / 4);
    ImageIO.write(buffer, "png", os);
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFBoolColumnCellRenderer.java

public void paint(Graphics g) {
    if (g == null) {
        return;//from  w w  w. j av  a  2  s. com
    }
    Rectangle bounds = getBounds();
    g.setColor(getBackground());
    g.fill3DRect(0, 0, bounds.width, bounds.height, true);
    g.setColor(getForeground());
    int xoffbox = (bounds.width - 16) / 2;
    int yoffbox = (bounds.height - 16) / 2;
    g.drawRect(xoffbox, yoffbox, 16, 16);
    Boolean useval;
    if (value instanceof Boolean) {
        useval = (Boolean) value;
    } else if (value instanceof String) {
        String s = (String) value;
        if (s.equals("true")) {
            useval = new Boolean(true);
        } else if (s.equals("false")) {
            useval = new Boolean(false);
        } else {
            useval = null;
        }
    } else {
        useval = null;
    }
    String str;
    if (useval == null) {
        str = "?";
    } else if (useval.booleanValue()) {
        str = "X";
    } else {
        str = null;
    }
    if (str != null) {
        FontMetrics fm = g.getFontMetrics();
        Rectangle sb = fm.getStringBounds(str, g).getBounds();
        int ascent = fm.getAscent();
        int leading = fm.getLeading();
        int sxoff = xoffbox + ((16 - sb.width) / 2);
        int syoff = yoffbox + ((16 - (leading + ascent)) / 2) + leading + ascent;
        g.drawString(str, sxoff, syoff);
    }
}

From source file:org.deegree.portal.standard.wms.control.DynLegendListener.java

/**
 * Draws the given symbol to the given image
 * //ww w  . j  a v a  2s. co  m
 * @param map
 *            Hashmap holding the properties of the legend
 * @param bi
 *            image of the legend
 * @param color
 *            color to fill the graphic
 * @return The drawn BufferedImage
 */
private BufferedImage drawSymbolsToBI(HashMap<String, Object> map, BufferedImage bi, Color color) {

    Graphics g = bi.getGraphics();
    g.setColor(color);
    g.fillRect(0, 0, bi.getWidth(), bi.getHeight());

    String[] layers = (String[]) map.get("NAMES");
    String[] titles = (String[]) map.get("TITLES");
    BufferedImage[] legs = (BufferedImage[]) map.get("IMAGES");
    int h = topMargin;
    for (int i = layers.length - 1; i >= 0; i--) {
        g.drawImage(legs[i], leftMargin, h, null);
        g.setColor(Color.BLACK);
        // just draw title if the flag has been set in listener configuration,
        // the legend image is less than a defined value and a legend image
        // (not missing) has been accessed
        if (useLayerTitle && legs[i].getHeight() < maxNNLegendSize && !missing.contains(layers[i])) {
            g.drawString(titles[i], leftMargin + legs[i].getWidth() + 10,
                    h + (int) (legs[i].getHeight() / 1.2));
        }
        h += legs[i].getHeight() + 5;
        if (separator != null && i > 0) {
            g.drawImage(separator, leftMargin, h, null);
            h += separator.getHeight() + 5;
        }
    }
    g.dispose();
    return bi;
}

From source file:edu.mit.fss.tutorial.part4.ControlPanel.java

@Override
public void paint(Graphics g) {
    // Calls the super-class paint method for the default background.
    super.paint(g);

    // Set color to gray and draw the x-axis (Y=0) and y=axis (X=0).
    g.setColor(Color.gray);/*from w ww  .  j  av a  2  s.  co  m*/
    g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
    g.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());

    // Make sure no changes to elements can take place while painting.
    synchronized (elements) {
        // For each surface element...
        for (SurfaceElement e : elements) {
            if (e instanceof MobileElement) {
                // If it is a MobileElement, use blue color.
                g.setColor(Color.blue);
            } else {
                // Otherwise use black color.
                g.setColor(Color.black);
            }
            // Determine the screen location for the element.
            int[] location = getScreenLocation(e.getPosition());

            // Fill an oval at the location (offset by half the oval size).
            g.fillOval(location[0] - ELEMENT_SIZE / 2, location[1] - ELEMENT_SIZE / 2, ELEMENT_SIZE,
                    ELEMENT_SIZE);

            // Draw the element name to the right of the oval, offset by
            // 2 pixels to the right and half the oval size vertically.
            g.drawString(e.getName(), location[0] + ELEMENT_SIZE / 2 + 2,
                    location[1] + ELEMENT_SIZE / 2 + ELEMENT_SIZE / 2);
        }
    }
}

From source file:javazoom.jlgui.player.amp.visual.ui.SpectrumTimeAnalyzer.java

public synchronized void process(float[] pLeft, float[] pRight, float pFrameRateRatioHint) {
    if (displayMode == DISPLAY_MODE_OFF)
        return;/*from  www .j  a v  a2s . c  om*/
    Graphics wGrp = getDoubleBuffer().getGraphics();
    wGrp.setColor(getBackground());
    wGrp.fillRect(0, 0, getSize().width, getSize().height);
    switch (displayMode) {
    case DISPLAY_MODE_SCOPE:
        drawScope(wGrp, stereoMerge(pLeft, pRight));
        break;
    case DISPLAY_MODE_SPECTRUM_ANALYSER:
        drawSpectrumAnalyser(wGrp, stereoMerge(pLeft, pRight), pFrameRateRatioHint);
        break;
    case DISPLAY_MODE_OFF:
        drawVUMeter(wGrp, pLeft, pRight, pFrameRateRatioHint);
        break;
    }
    // -- Show FPS if necessary.
    if (showFPS) {
        // -- Calculate FPS.
        if (System.currentTimeMillis() >= lfu + 1000) {
            lfu = System.currentTimeMillis();
            fps = fc;
            fc = 0;
        }
        fc++;
        wGrp.setColor(Color.yellow);
        wGrp.drawString("FPS: " + fps + " (FRRH: " + pFrameRateRatioHint + ")", 0, height - 1);
    }
    if (getGraphics() != null)
        getGraphics().drawImage(getDoubleBuffer(), 0, 0, null);
    //      repaint();
    //      try {
    //          EventQueue.invokeLater( new AWTPaintSynchronizer() );
    //      } catch ( Exception pEx ) {
    //          // -- Ignore exception.
    //          pEx.printStackTrace();
    //      }
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFTimeColumnCellRenderer.java

public void paint(Graphics g) {
    if (g == null) {
        return;//  w w w.j ava2s  . c  om
    }
    Rectangle bounds = getBounds();
    g.setColor(getBackground());
    g.fill3DRect(0, 0, bounds.width, bounds.height, true);
    g.setColor(getForeground());
    String str;
    if (value instanceof Calendar) {
        Calendar cal = (Calendar) value;
        Format fmt = getDefaultFormat();
        Calendar withoutDate = Calendar.getInstance();
        withoutDate.clear();
        withoutDate.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
        withoutDate.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
        withoutDate.set(Calendar.SECOND, cal.get(Calendar.SECOND));
        str = fmt.format(withoutDate.getTime());
    } else if (value instanceof String) {
        str = (String) value;
    } else {
        str = null;
    }
    if (str != null) {
        int firstNewline = str.indexOf('\n');
        if (firstNewline < 0) {
            firstNewline = str.indexOf('\r');
            if (firstNewline < 0) {
                firstNewline = str.indexOf('\f');
                if (firstNewline < 0) {
                    firstNewline = str.length();
                }
            }
        }
        String firstLine = str.substring(0, firstNewline);
        FontMetrics fm = g.getFontMetrics();
        int ascent = fm.getAscent();
        int leading = fm.getLeading();
        g.drawString(firstLine, 4, leading + ascent + 4);
    }
}

From source file:org.openlegacy.terminal.render.DefaultTerminalSnapshotImageRenderer.java

private void markBackgroundAndInputFields(TerminalSnapshot terminalSnapshot, Graphics graphics) {
    int endX;/*from  ww w .  j a  v a  2  s .  co  m*/
    List<TerminalField> fields = terminalSnapshot.getFields();
    setDefaultColor(graphics);
    for (TerminalField terminalField : fields) {
        TerminalPosition position = terminalField.getPosition();
        // -1 - pixels is 0 based , column is 1 based
        int startX = toWidth(position.getColumn() - 1 + leftColumnsOffset);
        int startY = toHeight(position.getRow());
        endX = toWidth(terminalField.getEndPosition().getColumn() + leftColumnsOffset);
        if (terminalField.isEditable()) {
            graphics.drawLine(startX, startY, endX, startY);
        }
        int rowHeight = toHeight(1);
        if (terminalField.getBackColor() != org.openlegacy.terminal.Color.BLACK) {
            graphics.setColor(SnapshotUtils.convertColor(terminalField.getBackColor()));
            //
            graphics.fillRect(startX, toHeight(position.getRow() - 1) + topPixelsOffset,
                    toWidth(terminalField.getLength()), rowHeight);
        }
    }

    if (drawFieldSeparators) {
        List<TerminalPosition> fieldSeperators = terminalSnapshot.getFieldSeperators();
        graphics.setColor(imageDefaultTextColor);
        for (TerminalPosition terminalPosition : fieldSeperators) {
            graphics.drawString("^", toWidth(terminalPosition.getColumn() - 1 + leftColumnsOffset),
                    toHeight(terminalPosition.getRow()));
        }
    }
}

From source file:jtrace.Scene.java

/**
 * Add a set of axes to an image.  If the object parameter is not null,
 * the axes corresponding to the object's coordinate system are drawn.
 * //www .  ja  v a 2 s.  c o  m
 * @param image Image generated using scene's camera
 * @param object (Possibly null) object
 */
private void renderAxes(BufferedImage image, SceneObject object) {

    Graphics gr = image.getGraphics();
    int[] origin, xhat, yhat, zhat;

    if (object == null) {
        origin = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.ZERO);
        xhat = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.PLUS_I);
        yhat = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.PLUS_J);
        zhat = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.PLUS_K);
    } else {
        origin = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.ZERO));
        xhat = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.PLUS_I));
        yhat = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.PLUS_J));
        zhat = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.PLUS_K));
    }

    String objName;
    if (object == null)
        objName = "";
    else
        objName = "(" + object.getClass().getSimpleName() + ")";

    gr.setColor(Color.red);
    gr.drawLine(origin[0], origin[1], xhat[0], xhat[1]);
    gr.setColor(Color.white);
    gr.drawString("x " + objName, xhat[0], xhat[1]);

    gr.setColor(Color.green);
    gr.drawLine(origin[0], origin[1], yhat[0], yhat[1]);
    gr.setColor(Color.white);
    gr.drawString("y " + objName, yhat[0], yhat[1]);

    gr.setColor(Color.blue);
    gr.drawLine(origin[0], origin[1], zhat[0], zhat[1]);
    gr.setColor(Color.white);
    gr.drawString("z " + objName, zhat[0], zhat[1]);
}