Example usage for java.awt Graphics2D setFont

List of usage examples for java.awt Graphics2D setFont

Introduction

In this page you can find the example usage for java.awt Graphics2D setFont.

Prototype

public abstract void setFont(Font font);

Source Link

Document

Sets this graphics context's font to the specified font.

Usage

From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java

private void processTextElement(Graphics2D g2, Element textElement) {

    int x = Integer.valueOf(textElement.getAttributeValue("X"));
    int y = Integer.valueOf(textElement.getAttributeValue("Y"));
    int width = Integer.valueOf(textElement.getAttributeValue("Width"));
    int height = Integer.valueOf(textElement.getAttributeValue("Height"));
    String alignment = textElement.getAttributeValue("TextAlignment");
    boolean multiline = Boolean.valueOf(textElement.getAttributeValue("Multiline").toLowerCase());
    boolean antiAlias = textElement.getAttributeValue("TextQuality").equalsIgnoreCase("antialias");

    Font font = parseFont(textElement.getAttributeValue("Font"));

    logger.info("Using font " + font);
    // now get the textim4java performance
    String text = textElement.getAttributeValue("Text");
    // if text matches pattern of %VARIABLE%{MODIFIER}
    logger.info("parsing token {}", text);
    Matcher matcher = pattern.matcher(text);
    int start = 0;
    while (matcher.find(start)) {
        // apply modification
        text = text.replace(matcher.group(), applyModifier(matcher.group()));
        start = matcher.end();//from  w  w  w  .  ja  v  a 2 s . c o m
    }
    BufferedImage tmpImage;
    if (width > 0 && height > 0) {
        // create a transparent tmpImage
        tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    } else {
        FontMetrics fm = g2.getFontMetrics(font);
        Rectangle outlineBounds = fm.getStringBounds(text, g2).getBounds();
        //         we need to create a transparent image to paint
        tmpImage = new BufferedImage(outlineBounds.width, outlineBounds.height, BufferedImage.TYPE_INT_ARGB);
    }
    Graphics2D g2d = tmpImage.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
    //        }
    g2d.setFont(font);
    Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor")));
    g2d.setColor(textColor);
    Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f);
    g2d.setComposite(comp);
    drawString(g2d, text, new Rectangle(0, 0, width, height), Align.valueOf(alignment), 0, multiline);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    tmpImage = processActions(textElement, tmpImage);

    ////        Graphics2D g2d = tmpImage.createGraphics();
    //        // set current font
    //        g2.setFont(font);
    ////        g2d.setComposite(AlphaComposite.Clear);
    ////        g2d.fillRect(0, 0, width, height);
    ////        g2d.setComposite(AlphaComposite.Src);
    //        // TODO: we have to parse it
    //        int strokeWidth = Integer.valueOf(textElement.getAttributeValue("StrokeWidth"));
    //        // the color of the outline
    //        if (strokeWidth > 0) {
    ////            Color strokeColor = new Color(Integer.valueOf(textElement.getAttributeValue("StrokeColor")));
    ////            AffineTransform affineTransform;
    ////            affineTransform = g2d.getTransform();
    ////            affineTransform.translate(width / 2 - (outlineBounds.width / 2), height / 2
    ////                    + (outlineBounds.height / 2));
    ////            g2d.transform(affineTransform);
    ////            // backup stroke width and color
    ////            Stroke originalStroke = g2d.getStroke();
    ////            Color originalColor = g2d.getColor();
    ////            g2d.setColor(strokeColor);
    ////            g2d.setStroke(new BasicStroke(strokeWidth));
    ////            g2d.draw(shape);
    ////            g2d.setClip(shape);
    ////            // restore stroke width and color
    ////            g2d.setStroke(originalStroke);
    ////            g2d.setColor(originalColor);
    //        }
    ////        // get the text color
    //        Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor")));
    //        g2.setColor(textColor);
    ////        g2d.setBackground(Color.BLACK);
    ////        g2d.setStroke(new BasicStroke(2));
    ////        g2d.setColor(Color.WHITE);
    //        // draw the text
    //
    //        drawString(g2, text, new Rectangle(x, y, width, height), Align.valueOf(alignment), 0, multiline);
    //        g2.drawString(text, x, y);
    //        Rectangle rect = new Rectangle(x, y, width, height); // defines the desired size and position
    //        FontMetrics fm = g2.getFontMetrics();
    //        FontRenderContext frc = g2.getFontRenderContext();
    //        TextLayout tl = new TextLayout(text, g2.getFont(), frc);
    //        AffineTransform transform = new AffineTransform();
    //        transform.setToTranslation(rect.getX(), rect.getY());
    //        if (Boolean.valueOf(textElement.getAttributeValue("AutoSize").toLowerCase())) {
    //            double scaleY
    //                    = rect.getHeight() / (double) (tl.getOutline(null).getBounds().getMaxY()
    //                    - tl.getOutline(null).getBounds().getMinY());
    //            transform.scale(rect.getWidth() / (double) fm.stringWidth(text), scaleY);
    //        }
    //        Shape shape = tl.getOutline(transform);
    //        g2.setClip(shape);
    //        g2.fill(shape.getBounds());
    //        if (antiAlias) {
    // we need to restore antialias to none
    //            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    //        }
    //        g2.drawString(text, x, y);
    // alway resize
    //        BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height);
    //        tmpImage = scaleFilter.filter(tmpImage, null);
    // draw the image to the source
    g2.drawImage(tmpImage, x, y, width, height, null);
    try {
        ScreenImage.writeImage(tmpImage, "/tmp/images/" + textElement.getAttributeValue("Name") + ".png");
    } catch (IOException ex) {

    }

}

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void fontName(final String fontFace) {
    Drawable command = new Drawable() {

        @Override//from w  w w  .j  a  v a  2 s. co  m
        public void draw(Graphics2D g2, TurtleState turtleState) {
            int style = turtleState.font.getStyle();
            int size = turtleState.font.getSize();

            turtleState.font = new Font(fontFace, style, size);

            g2.setFont(turtleState.font);
        }

        @Override
        public void addListener(DrawListener listener) {
        }

        @Override
        public void removeListener(DrawListener listener) {
        }

        @Override
        public Drawable cloneDrawable() {
            return this;
        }
    };
    submitCommand(command);
}

From source file:org.optaplanner.examples.coachshuttlegathering.swingui.CoachShuttleGatheringWorldPanel.java

public void resetPanel(CoachShuttleGatheringSolution solution) {
    translator = new LatitudeLongitudeTranslator();
    for (RoadLocation location : solution.getLocationList()) {
        translator.addCoordinates(location.getLatitude(), location.getLongitude());
    }// w  w w.  j  a v a  2  s  . co  m

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

    Graphics2D g = createCanvas(width, height);
    g.setColor(TangoColorFactory.ORANGE_3);
    RoadLocation hubLocation = solution.getHub().getLocation();
    translator.drawSquare(g, hubLocation.getLongitude(), hubLocation.getLatitude(), 5);
    for (BusStop stop : solution.getStopList()) {
        RoadLocation location = stop.getLocation();
        g.setColor((stop.getPassengerQuantity() <= 0) ? TangoColorFactory.ALUMINIUM_4
                : (stop.getTransportTimeToHub() == null) ? TangoColorFactory.ORANGE_2
                        : (stop.getTransportTimeRemainder() < 0) ? TangoColorFactory.SCARLET_2
                                : TangoColorFactory.ORANGE_2);
        translator.drawSquare(g, location.getLongitude(), location.getLatitude(), 3, stop.getTransportLabel());
    }
    List<Bus> busList = solution.getBusList();
    g.setColor(TangoColorFactory.ALUMINIUM_2);
    g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE));
    for (Bus bus : busList) {
        RoadLocation location = bus.getLocation();
        g.setColor(bus instanceof Coach ? TangoColorFactory.ORANGE_1 : TangoColorFactory.ALUMINIUM_2);
        translator.drawSquare(g, location.getLongitude(), location.getLatitude(), 3,
                StringUtils.abbreviate(bus.getName(), 20));
    }
    int colorIndex = 0;
    for (Bus bus : busList) {
        g.setColor(TangoColorFactory.SEQUENCE_2[colorIndex]);
        BusStop lastStop = null;
        for (BusStop stop = bus.getNextStop(); stop != null; stop = stop.getNextStop()) {
            RoadLocation previousLocation = stop.getPreviousBusOrStop().getLocation();
            RoadLocation location = stop.getLocation();
            translator.drawRoute(g, previousLocation.getLongitude(), previousLocation.getLatitude(),
                    location.getLongitude(), location.getLatitude(), false, false);
            lastStop = stop;
        }
        if (lastStop != null || bus instanceof Coach) {
            RoadLocation lastStopLocation = lastStop == null ? bus.getLocation() : lastStop.getLocation();
            StopOrHub destination = bus.getDestination();
            if (destination != null) {
                RoadLocation destinationLocation = destination.getLocation();
                translator.drawRoute(g, lastStopLocation.getLongitude(), lastStopLocation.getLatitude(),
                        destinationLocation.getLongitude(), destinationLocation.getLatitude(), false, true);
            }
        }
        colorIndex = (colorIndex + 1) % TangoColorFactory.SEQUENCE_2.length;
    }
    repaint();
}

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void fontStyle(final int style) {
    Drawable command = new Drawable() {

        @Override// w w w  .jav a2s  .  c  om
        public void draw(Graphics2D g2, TurtleState turtleState) {
            String fontName = turtleState.font.getFontName();
            int size = turtleState.font.getSize();

            turtleState.font = new Font(fontName, style, size);

            g2.setFont(turtleState.font);
        }

        @Override
        public void addListener(DrawListener listener) {
        }

        @Override
        public void removeListener(DrawListener listener) {
        }

        @Override
        public Drawable cloneDrawable() {
            return this;
        }
    };
    submitCommand(command);
}

From source file:org.openaltimeter.desktopapp.annotations.XYVarioAnnotation.java

@Override
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {
    // draw line//from   w w w  .j  a v a  2s  . co m
    super.draw(g2, plot, dataArea, domainAxis, rangeAxis, rendererIndex, info);

    // draw text
    PlotOrientation orientation = plot.getOrientation();
    RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(plot.getDomainAxisLocation(), orientation);
    RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(plot.getRangeAxisLocation(), orientation);

    float anchorX = (float) domainAxis.valueToJava2D((x1 + x2) / 2, dataArea, domainEdge);
    float anchorY = (float) rangeAxis.valueToJava2D((y1 + y2) / 2, dataArea, rangeEdge);

    if (orientation == PlotOrientation.HORIZONTAL) {
        float tempAnchor = anchorX;
        anchorX = anchorY;
        anchorY = tempAnchor;
    }

    g2.setFont(getFont());
    g2.setPaint(getPaint());

    TextUtilities.drawRotatedString(getText(), g2, anchorX + this.offset, anchorY - OFFSET_SIZE,
            getTextAnchor(), getRotationAngle(), getRotationAnchor());

    g2.setPaint(Color.GRAY);
    int jx1 = (int) domainAxis.valueToJava2D(x1, dataArea, domainEdge);
    int jx2 = (int) domainAxis.valueToJava2D(x2, dataArea, domainEdge);
    int jy1 = (int) rangeAxis.valueToJava2D(y1, dataArea, rangeEdge);
    int jy2 = (int) rangeAxis.valueToJava2D(y2, dataArea, rangeEdge);

    TextUtilities.drawRotatedString(getText2(), g2, (jx1 + jx2) / 2, jy1 + LIMB_TEXT_OFFSET, getTextAnchor(),
            getRotationAngle(), getRotationAnchor());

    g2.drawLine(jx1, jy1, jx2, jy1);
    g2.drawLine(jx2, jy1, jx2, jy2);

}

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void fontSize(final int size) {
    Drawable command = new Drawable() {

        @Override//from w  w  w  .  j a  v a 2 s.  c  o m
        public void draw(Graphics2D g2, TurtleState turtleState) {
            String fontName = turtleState.font.getFontName();
            int style = turtleState.font.getStyle();

            turtleState.font = new Font(fontName, style, size);

            g2.setFont(turtleState.font);
        }

        @Override
        public void addListener(DrawListener listener) {
        }

        @Override
        public void removeListener(DrawListener listener) {
        }

        @Override
        public Drawable cloneDrawable() {
            return this;
        }
    };
    submitCommand(command);
}

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);/*from   w w w  .j a va  2 s. co m*/
    g.setFont(new Font("helvetica", Font.PLAIN, 16));
    g.drawString(message, 20, 430);
    SplashScreen.getSplashScreen().update();

}

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

/**
 * Export this frame as an image.//from w  w  w.j av  a2s . c om
 */
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:coolmap.canvas.datarenderer.renderer.impl.NumberToColor.java

@Override
public void prepareGraphics(Graphics2D g2D) {
    g2D.setFont(UI.fontMono.deriveFont(12f));
}

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)
   {/*w w  w  .java2  s.c  om*/
      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);
   }
}