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.gitools.ui.app.heatmap.drawer.AbstractHeatmapDrawer.java

protected static void paintCell(Decoration decoration, Color gridColor, int gridSize, int offsetX, int offsetY,
        int width, int height, Graphics2D g, Rectangle box) {

    int y = box.y + offsetY;
    int x = box.x + offsetX;

    g.setColor(decoration.getBgColor());
    g.fillRect(x, y, width, height);/* ww w .  ja  v a  2  s  .co  m*/

    g.setColor(gridColor);
    g.fillRect(x, y + height, width, gridSize);

    String text = decoration.getFormatedValue();
    if (!StringUtils.isEmpty(text)) {

        Font font = g.getFont();

        boolean isRotated = decoration.isRotate();

        int fontHeight = (int) font.getSize2D();

        if (fontHeight <= (isRotated ? width : height)) {

            int textWidth = (int) g.getFontMetrics().getStringBounds(text, g).getWidth();
            //TODO: textWidth depends on SuperScript

            if (textWidth < (isRotated ? height : width)) {

                int leftMargin = ((width - textWidth) / 2) + 1;
                int bottomMargin = ((height - fontHeight) / 2) + 1;

                if (isRotated) {
                    leftMargin = ((width - fontHeight) / 2) + 1;
                    bottomMargin = height - (((height - textWidth) / 2));
                }

                g.setColor(Colors.bestForegroundColor(decoration.getBgColor()));
                if (text.matches("[0-9\\.]+e-?[0-9]+")) {
                    int e_pos = text.indexOf("e") + 3;
                    text = text.replaceAll("e(-?[0-9]+)", "10$1");
                    int superscriptEnd = text.length();
                    AttributedString attText = new AttributedString(text);
                    attText.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, e_pos,
                            superscriptEnd);
                    if (isRotated) {
                        g.rotate(radianAngle90);
                        g.drawString(attText.getIterator(), y + height - bottomMargin, -x - leftMargin - 1);
                        g.rotate(-radianAngle90);
                    } else {
                        g.drawString(attText.getIterator(), x + leftMargin, y + height - bottomMargin);
                    }
                } else {

                    if (isRotated) {
                        g.rotate(radianAngle90);
                        g.drawString(text, y + height - bottomMargin, -x - leftMargin - 1);

                        if ("CoCA-08".equals(text)) {
                            System.out.println("x = " + x + " leftMargin = " + leftMargin + " width = " + width
                                    + " fontHeight = " + fontHeight);
                        }

                        g.rotate(-radianAngle90);
                    } else {
                        g.drawString(text, x + leftMargin, y + height - bottomMargin);
                    }
                }
            }
        }
    }

}

From source file:Chart.java

 public void paintComponent(Graphics g)
{
   Graphics2D g2 = (Graphics2D) g;

   // compute the minimum and maximum values
   if (values == null) return;
   double minValue = 0;
   double maxValue = 0;
   for (double v : values)
   {//from   w w w. ja  v a 2  s .c  o m
      if (minValue > v) minValue = v;
      if (maxValue < v) maxValue = v;
   }
   if (maxValue == minValue) return;

   int panelWidth = getWidth();
   int panelHeight = getHeight();

   Font titleFont = new Font("SansSerif", Font.BOLD, 20);
   Font labelFont = new Font("SansSerif", Font.PLAIN, 10);

   // compute the extent of the title
   FontRenderContext context = g2.getFontRenderContext();
   Rectangle2D titleBounds = titleFont.getStringBounds(title, context);
   double titleWidth = titleBounds.getWidth();
   double top = titleBounds.getHeight();

   // draw the title
   double y = -titleBounds.getY(); // ascent
   double x = (panelWidth - titleWidth) / 2;
   g2.setFont(titleFont);
   g2.drawString(title, (float) x, (float) y);

   // compute the extent of the bar labels
   LineMetrics labelMetrics = labelFont.getLineMetrics("", context);
   double bottom = labelMetrics.getHeight();

   y = panelHeight - labelMetrics.getDescent();
   g2.setFont(labelFont);

   // get the scale factor and width for the bars
   double scale = (panelHeight - top - bottom) / (maxValue - minValue);
   int barWidth = panelWidth / values.length;

   // draw the bars
   for (int i = 0; i < values.length; i++)
   {
      // get the coordinates of the bar rectangle
      double x1 = i * barWidth + 1;
      double y1 = top;
      double height = values[i] * scale;
      if (values[i] >= 0) y1 += (maxValue - values[i]) * scale;
      else
      {
         y1 += maxValue * scale;
         height = -height;
      }

      // fill the bar and draw the bar outline
      Rectangle2D rect = new Rectangle2D.Double(x1, y1, barWidth - 2, height);
      g2.setPaint(Color.RED);
      g2.fill(rect);
      g2.setPaint(Color.BLACK);
      g2.draw(rect);

      // draw the centered label below the bar
      Rectangle2D labelBounds = labelFont.getStringBounds(names[i], context);

      double labelWidth = labelBounds.getWidth();
      x = x1 + (barWidth - labelWidth) / 2;
      g2.drawString(names[i], (float) x, (float) y);
   }
}

From source file:org.pmedv.core.app.SplashScreen.java

/**
 * Show the splash screen./*from   w  w  w. j  av  a  2  s  .c o  m*/
 */
public void splash() {

    window = new JWindow();
    // TODO : What was this for?
    // AWTUtilities.setWindowOpaque(window, false);

    if (image == null) {
        image = loadImage(imageResourcePath);
        if (image == null) {
            return;
        }
    }

    MediaTracker mediaTracker = new MediaTracker(window);
    mediaTracker.addImage(image, 0);

    try {
        mediaTracker.waitForID(0);
    } catch (InterruptedException e) {
        log.error("Interrupted while waiting for splash image to load.");
    }

    int width = image.getWidth(null);
    int height = image.getHeight(null);

    BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = (Graphics2D) bimg.createGraphics();

    g2d.drawImage(image, 0, 0, null);
    g2d.setColor(Color.BLACK);
    g2d.setFont(new Font("Arial", Font.BOLD, 10));
    InputStream is = getClass().getClassLoader().getResourceAsStream("application.properties");
    Properties properties = new Properties();
    try {
        properties.load(is);
    } catch (IOException e1) {
        properties.setProperty("version", "not set");
    }

    String version = properties.getProperty("version");

    File f = new File("build.number");

    properties = new Properties();

    try {
        properties.load(new FileReader(f));
    } catch (IOException e1) {
        properties.setProperty("build.number", "00");
    }

    String buildNumber = properties.getProperty("build.number");

    g2d.drawString("Version " + version + "." + buildNumber, 400, 305);

    JLabel panelImage = new JLabel(new ImageIcon(bimg));

    window.getContentPane().add(panelImage);
    window.getContentPane().add(progressBar, BorderLayout.SOUTH);
    window.pack();

    WindowUtils.center(window);

    window.setVisible(true);
}

From source file:com.neophob.sematrix.generator.Textwriter.java

/**
 * create image./*from   w ww .ja v a  2  s .  c o  m*/
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    maxXPos = (int) (0.5f + rect.getWidth()) + 5;
    ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_INT_RGB);
    g2 = img.createGraphics();

    g2.setColor(color);
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.drawString(text, xpos, ypos);
    DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer();
    textBuffer = dbi.getData();
    g2.dispose();

    wait = 0;
    xofs = 0;
    scrollRight = false;
}

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

/**
 * Export this frame as an image.//  w  ww . j  a v  a  2  s  .c  o m
 */
public BufferedImage frameToImage(int baseSelected) {
    BufferedImage bufferedImage = new BufferedImage(graphPane.getWidth(), graphPane.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bufferedImage.createGraphics();
    graphPane.setRenderForced();
    graphPane.forceFullHeight();
    graphPane.render(g2);
    graphPane.unforceFullHeight();
    g2.setColor(Color.black);
    if (baseSelected > 0) {
        double h = (double) graphPane.getHeight();
        double spos = graphPane.transformXPos(baseSelected);
        g2.draw(new Line2D.Double(spos, 0.0, spos, h));
        double rpos = graphPane.transformXPos(baseSelected + 1);
        g2.draw(new Line2D.Double(rpos, 0.0, rpos, h));
    }
    g2.setFont(new Font(null, Font.BOLD, 13));
    g2.drawString(tracks[0].getName(), 2, 15);
    return bufferedImage;
}

From source file:com.brainflow.application.toplevel.Brainflow.java

private void splashMessage(String message) {
    Graphics2D g = SplashScreen.getSplashScreen().createGraphics();
    //g.setComposite(AlphaComposite.Clear);
    //g.fillRect(20,430,100,460);
    //g.setPaintMode();
    g.setColor(Color.WHITE);//w  w  w .  j  av a  2 s. com
    g.setFont(new Font("helvetica", Font.PLAIN, 16));
    g.drawString(message, 20, 430);
    SplashScreen.getSplashScreen().update();

}

From source file:MainClass.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Font font = new Font("Serif", Font.PLAIN, 72);
    g2.setFont(font);/*  w ww  .  j av  a2  s .c  om*/

    String s = "www.java2s.com";
    float x = 50, y = 150;

    FontRenderContext frc = g2.getFontRenderContext();
    float width = (float) font.getStringBounds(s, frc).getWidth();
    Line2D baseline = new Line2D.Float(x, y, x + width, y);
    g2.setPaint(Color.lightGray);
    g2.draw(baseline);

    // Draw the ascent.
    LineMetrics lm = font.getLineMetrics(s, frc);
    Line2D ascent = new Line2D.Float(x, y - lm.getAscent(), x + width, y - lm.getAscent());
    g2.draw(ascent);

    // Draw the descent.
    Line2D descent = new Line2D.Float(x, y + lm.getDescent(), x + width, y + lm.getDescent());
    g2.draw(descent);

    // Draw the leading.
    Line2D leading = new Line2D.Float(x, y + lm.getDescent() + lm.getLeading(), x + width,
            y + lm.getDescent() + lm.getLeading());
    g2.draw(leading);

    // Render the string.
    g2.setPaint(Color.black);
    g2.drawString(s, x, y);
}

From source file:org.tinymediamanager.ui.components.ImageLabel.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (scaledImage != null) {
        int originalWidth = scaledImage.getWidth(null);
        int originalHeight = scaledImage.getHeight(null);

        // calculate new height/width
        int newWidth = 0;
        int newHeight = 0;

        int offsetX = 0;
        int offsetY = 0;

        if (drawBorder && !drawFullWidth) {
            Point size = ImageCache.calculateSize(this.getWidth() - 8, this.getHeight() - 8, originalWidth,
                    originalHeight, true);

            // calculate offsets
            if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) {
                offsetX = this.getWidth() - size.x - 8;
            }/*from www  .j av a 2  s  .c  o  m*/

            if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) {
                offsetY = this.getHeight() - size.y - 8;
            }

            if (position == Position.CENTER) {
                offsetX = (this.getWidth() - size.x - 8) / 2;
                offsetY = (this.getHeight() - size.y - 8) / 2;
            }

            newWidth = size.x;
            newHeight = size.y;

            // when the image size differs too much - reload and rescale the original image
            recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight);

            g.setColor(Color.BLACK);
            g.drawRect(offsetX, offsetY, size.x + 7, size.y + 7);
            g.setColor(Color.WHITE);
            g.fillRect(offsetX + 1, offsetY + 1, size.x + 6, size.y + 6);
            // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX + 4, offsetY + 4, newWidth, newHeight, this);
            g.drawImage(scaledImage, offsetX + 4, offsetY + 4, newWidth, newHeight, this);
        } else {
            Point size = null;
            if (drawFullWidth) {
                size = new Point(this.getWidth(), this.getWidth() * originalHeight / originalWidth);
            } else {
                size = ImageCache.calculateSize(this.getWidth(), this.getHeight(), originalWidth,
                        originalHeight, true);
            }

            // calculate offsets
            if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) {
                offsetX = this.getWidth() - size.x;
            }

            if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) {
                offsetY = this.getHeight() - size.y;
            }

            if (position == Position.CENTER) {
                offsetX = (this.getWidth() - size.x) / 2;
                offsetY = (this.getHeight() - size.y) / 2;
            }

            newWidth = size.x;
            newHeight = size.y;

            // when the image size differs too much - reload and rescale the original image
            recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight);

            // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX, offsetY, newWidth, newHeight, this);
            g.drawImage(scaledImage, offsetX, offsetY, newWidth, newHeight, this);
        }
    } else {
        // draw border and background
        if (drawBorder) {
            g.setColor(Color.BLACK);
            g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
            if (getParent().isOpaque()) {
                g.setColor(getParent().getBackground());
                g.fillRect(1, 1, this.getWidth() - 2, this.getHeight() - 2);
            }
        }

        // calculate diagonal
        int diagonalSize = (int) Math
                .sqrt(this.getWidth() * this.getWidth() + this.getHeight() * this.getHeight());

        // draw text
        String text = "";
        if (alternativeText != null) {
            text = alternativeText;
        } else {
            text = BUNDLE.getString("image.nonefound"); //$NON-NLS-1$
        }
        if (!getParent().isOpaque()) {
            text = "";
        }
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        AffineTransform orig = g2.getTransform();
        AffineTransform at = new AffineTransform(orig);
        at.translate(0, this.getHeight());
        at.rotate(this.getWidth(), -this.getHeight());
        g2.setTransform(at);
        g2.setColor(Color.BLACK);
        g2.setFont(FONT);

        FontMetrics fm = g2.getFontMetrics();
        int x = (diagonalSize - fm.stringWidth(text)) / 2;
        int y = (fm.getAscent() - fm.getDescent()) / 2;

        g2.drawString(text, x, y);
        // g2.drawLine(0, 0, diagonalSize, 0);
        at.translate(0, -this.getHeight());
        g2.setTransform(orig);
    }
}

From source file:org.optaplanner.examples.tsp.swingui.TspWorldPanel.java

public void resetPanel(TravelingSalesmanTour travelingSalesmanTour) {
    translator = new LatitudeLongitudeTranslator();
    for (Location location : travelingSalesmanTour.getLocationList()) {
        translator.addCoordinates(location.getLatitude(), location.getLongitude());
    }//from ww w .  j a va 2  s.  c o m

    Dimension size = getSize();
    double width = size.getWidth();
    double height = size.getHeight();
    translator.prepareFor(width, height);

    Graphics2D g = createCanvas(width, height);
    String tourName = travelingSalesmanTour.getName();
    if (tourName.startsWith("europe")) {
        g.drawImage(europaBackground.getImage(), 0, 0, translator.getImageWidth(), translator.getImageHeight(),
                this);
    }
    g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE));
    g.setColor(TangoColorFactory.PLUM_2);
    List<Visit> visitList = travelingSalesmanTour.getVisitList();
    for (Visit visit : visitList) {
        Location location = visit.getLocation();
        int x = translator.translateLongitudeToX(location.getLongitude());
        int y = translator.translateLatitudeToY(location.getLatitude());
        g.fillRect(x - 1, y - 1, 3, 3);
        if (location.getName() != null && visitList.size() <= 500) {
            g.drawString(StringUtils.abbreviate(location.getName(), 20), x + 3, y - 3);
        }
    }
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    Domicile domicile = travelingSalesmanTour.getDomicile();
    Location domicileLocation = domicile.getLocation();
    int domicileX = translator.translateLongitudeToX(domicileLocation.getLongitude());
    int domicileY = translator.translateLatitudeToY(domicileLocation.getLatitude());
    g.fillRect(domicileX - 2, domicileY - 2, 5, 5);
    if (domicileLocation.getName() != null && visitList.size() <= 500) {
        g.drawString(domicileLocation.getName(), domicileX + 3, domicileY - 3);
    }
    Set<Visit> needsBackToDomicileLineSet = new HashSet<Visit>(visitList);
    for (Visit trailingVisit : visitList) {
        if (trailingVisit.getPreviousStandstill() instanceof Visit) {
            needsBackToDomicileLineSet.remove(trailingVisit.getPreviousStandstill());
        }
    }
    g.setColor(TangoColorFactory.CHOCOLATE_1);
    for (Visit visit : visitList) {
        if (visit.getPreviousStandstill() != null) {
            Location previousLocation = visit.getPreviousStandstill().getLocation();
            Location location = visit.getLocation();
            translator.drawRoute(g, previousLocation.getLongitude(), previousLocation.getLatitude(),
                    location.getLongitude(), location.getLatitude(), location instanceof AirLocation, false);
            // Back to domicile line
            if (needsBackToDomicileLineSet.contains(visit)) {
                translator.drawRoute(g, location.getLongitude(), location.getLatitude(),
                        domicileLocation.getLongitude(), domicileLocation.getLatitude(),
                        location instanceof AirLocation, true);
            }
        }
    }
    // Drag
    if (dragSourceStandstill != null) {
        g.setColor(TangoColorFactory.CHOCOLATE_2);
        Location sourceLocation = dragSourceStandstill.getLocation();
        Location targetLocation = dragTargetStandstill.getLocation();
        translator.drawRoute(g, sourceLocation.getLongitude(), sourceLocation.getLatitude(),
                targetLocation.getLongitude(), targetLocation.getLatitude(),
                sourceLocation instanceof AirLocation, dragTargetStandstill instanceof Domicile);
    }
    // Legend
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    g.fillRect(5, (int) height - 15 - TEXT_SIZE, 5, 5);
    g.drawString("Domicile", 15, (int) height - 10 - TEXT_SIZE);
    g.setColor(TangoColorFactory.PLUM_2);
    g.fillRect(6, (int) height - 9, 3, 3);
    g.drawString("Visit", 15, (int) height - 5);
    g.setColor(TangoColorFactory.ALUMINIUM_5);
    String locationsSizeString = travelingSalesmanTour.getLocationList().size() + " locations";
    g.drawString(locationsSizeString, ((int) width - g.getFontMetrics().stringWidth(locationsSizeString)) / 2,
            (int) height - 5);
    if (travelingSalesmanTour.getDistanceType() == DistanceType.AIR_DISTANCE) {
        String leftClickString = "Left click and drag between 2 locations to connect them.";
        g.drawString(leftClickString, (int) width - 5 - g.getFontMetrics().stringWidth(leftClickString),
                (int) height - 10 - TEXT_SIZE);
        String rightClickString = "Right click anywhere on the map to add a visit.";
        g.drawString(rightClickString, (int) width - 5 - g.getFontMetrics().stringWidth(rightClickString),
                (int) height - 5);
    }
    // Show soft score
    g.setColor(TangoColorFactory.ORANGE_3);
    SimpleLongScore score = travelingSalesmanTour.getScore();
    if (score != null) {
        String distanceString = travelingSalesmanTour.getDistanceString(NUMBER_FORMAT);
        g.setFont(g.getFont().deriveFont(Font.BOLD, (float) TEXT_SIZE * 2));
        g.drawString(distanceString, (int) width - g.getFontMetrics().stringWidth(distanceString) - 10,
                (int) height - 15 - 2 * TEXT_SIZE);
    }
    repaint();
}

From source file:ImageOps.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Create a BufferedImage big enough to hold the Image loaded
    // in the constructor. Then copy that image into the new
    // BufferedImage object so that we can process it.
    BufferedImage bimage = new BufferedImage(image.getWidth(this), image.getHeight(this),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D ig = bimage.createGraphics();
    ig.drawImage(image, 0, 0, this); // copy the image

    // Set some default graphics attributes
    g.setFont(new Font("SansSerif", Font.BOLD, 12)); // 12pt bold text
    g.setColor(Color.green); // Draw in green
    g.translate(10, 10); // Set some margins

    // Loop through the filters
    for (int i = 0; i < filters.length; i++) {
        // If the filter is null, draw the original image, otherwise,
        // draw the image as processed by the filter
        if (filters[i] == null)
            g.drawImage(bimage, 0, 0, this);
        else//from w  ww .  ja  v a 2s .c om
            g.drawImage(filters[i].filter(bimage, null), 0, 0, this);
        g.drawString(filterNames[i], 0, 205); // Label the image
        g.translate(137, 0); // Move over
        if (i % 4 == 3)
            g.translate(-137 * 4, 215); // Move down after 4
    }
}