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:edu.cuny.cat.ui.ClockPanel.java

@Override
public void setup(final ParameterDatabase parameters, final Parameter base) {
    clock = GameController.getInstance().getClock();

    dataset = new DefaultValueDataset();

    meterplot = new MyMeterPlot(dataset) {
        /**/*from ww  w  . j av  a2  s . c  o  m*/
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        protected void drawValueLabel(final Graphics2D g2, final Rectangle2D area) {
            g2.setFont(getValueFont());
            g2.setPaint(getValuePaint());
            String valueStr = "No value";
            if (dataset != null) {
                final Number n = dataset.getValue();
                if (n != null) {
                    if (n.intValue() == 0) {
                        valueStr = "to start";
                    } else if (n.intValue() == clock.getGameLen() * clock.getDayLen()) {
                        valueStr = "done";
                    } else {
                        valueStr = "day " + (n.intValue() / clock.getDayLen()) + ", round "
                                + (n.intValue() % clock.getDayLen());
                    }
                }
            }
            final float x = (float) area.getCenterX();
            final float y = (float) area.getCenterY() + MeterPlot.DEFAULT_CIRCLE_SIZE;
            TextUtilities.drawAlignedString(valueStr, g2, x, y, TextAnchor.TOP_CENTER);
        }

    };
    meterplot.setRange(new Range(0, clock.getDayLen() * clock.getGameLen()));

    meterplot.setNeedlePaint(
            parameters.getColorWithDefault(base.push(ClockPanel.P_NEEDLE), null, Color.darkGray));

    meterplot.setDialBackgroundPaint(new Color(0, 255, 0, 64));
    meterplot.setDialOutlinePaint(Color.gray);
    meterplot.setDialShape(DialShape.CHORD);

    meterplot.setMeterAngle(parameters.getIntWithDefault(base.push(ClockPanel.P_ANGLE), null, 260));

    meterplot.setTickLabelsVisible(true);
    meterplot.setTickLabelFont(new Font("Dialog", 1, 10));
    meterplot.setTickLabelPaint(Color.darkGray);
    meterplot.setTickSize(clock.getDayLen());
    meterplot.setTickPaint(Color.lightGray);

    meterplot.setValuePaint(Color.black);
    meterplot.setValueFont(new Font("Dialog", 1, 14));
    meterplot.setUnits("");
    meterplot.setTickLabelFormat(new NumberFormat() {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public StringBuffer format(final double number, final StringBuffer toAppendTo,
                final FieldPosition pos) {
            return format((long) number, toAppendTo, pos);
        }

        @Override
        public StringBuffer format(final long number, final StringBuffer toAppendTo, final FieldPosition pos) {

            if (number % clock.getDayLen() == 0) {
                toAppendTo.append(String.valueOf(number / clock.getDayLen()));
            }
            return toAppendTo;
        }

        @Override
        public Number parse(final String source, final ParsePosition parsePosition) {
            return null;
        }

    });

    final JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, meterplot, false);

    final ChartPanel panel = new ChartPanel(chart);
    panel.setPreferredSize(new Dimension(parameters.getIntWithDefault(base.push(ClockPanel.P_WIDTH), null, 200),
            parameters.getIntWithDefault(base.push(ClockPanel.P_HEIGHT), null, 200)));

    add(panel, BorderLayout.CENTER);

    initIterationLabel();

    initScoreReport();
}

From source file:net.sf.mzmine.modules.visualization.scatterplot.scatterplotchart.ScatterPlotRenderer.java

/**
 * Draws an item label./*from  w w  w . j a v a 2 s .com*/
 * 
 * @param g2
 *            the graphics device.
 * @param orientation
 *            the orientation.
 * @param dataset
 *            the dataset.
 * @param series
 *            the series index (zero-based).
 * @param item
 *            the item index (zero-based).
 * @param x
 *            the x coordinate (in Java2D space).
 * @param y
 *            the y coordinate (in Java2D space).
 * @param negative
 *            indicates a negative value (which affects the item label
 *            position).
 */
protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation, XYDataset dataset, int series,
        int item, double x, double y, boolean negative) {

    XYItemLabelGenerator generator = getItemLabelGenerator(series, item);
    Font labelFont = getItemLabelFont(series, item);
    g2.setFont(labelFont);
    String label = generator.generateLabel(dataset, series, item);

    if ((label == null) || (label.length() == 0))
        return;

    // get the label position..
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(series, item);
    } else {
        position = getNegativeItemLabelPosition(series, item);
    }

    // work out the label anchor point...
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), x, y, orientation);

    FontMetrics metrics = g2.getFontMetrics(labelFont);
    int width = SwingUtilities.computeStringWidth(metrics, label) + 2;
    int height = metrics.getHeight();

    int X = (int) (anchorPoint.getX() - (width / 2));
    int Y = (int) (anchorPoint.getY() - (height));

    g2.setPaint(searchColor);
    g2.fillRect(X, Y, width, height);

    super.drawItemLabel(g2, orientation, dataset, series, item, x, y, negative);

}

From source file:CompositeEffects.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;

    // fill the background
    g.setPaint(new Color(175, 175, 175));
    g.fillRect(0, 0, getWidth(), getHeight());

    // Set text attributes
    g.setColor(Color.black);/*from w w  w . j  a va  2s. co  m*/
    g.setFont(new Font("SansSerif", Font.BOLD, 12));

    // Draw the unmodified image
    g.translate(10, 10);
    g.drawImage(cover, 0, 0, this);
    g.drawString("SRC_OVER", 0, COVERHEIGHT + 15);

    // Draw the cover again, using AlphaComposite to make the opaque
    // colors of the image 50% translucent
    g.translate(COVERWIDTH + 10, 0);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    g.drawImage(cover, 0, 0, this);

    // Restore the pre-defined default Composite for the screen, so
    // opaque colors stay opaque.
    g.setComposite(AlphaComposite.SrcOver);
    // Label the effect
    g.drawString("SRC_OVER, 50%", 0, COVERHEIGHT + 15);

    // Now get an offscreen image to work with. In order to achieve
    // certain compositing effects, the drawing surface must support
    // transparency. Onscreen drawing surfaces cannot, so we have to do the
    // compositing in an offscreen image that is specially created to have
    // an "alpha channel", then copy the final result to the screen.
    BufferedImage offscreen = new BufferedImage(COVERWIDTH, COVERHEIGHT, BufferedImage.TYPE_INT_ARGB);

    // First, fill the image with a color gradient background that varies
    // left-to-right from opaque to transparent yellow
    Graphics2D osg = offscreen.createGraphics();
    osg.setPaint(new GradientPaint(0, 0, Color.yellow, COVERWIDTH, 0, new Color(255, 255, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now copy the cover image on top of this, but use the DstOver rule
    // which draws it "underneath" the existing pixels, and allows the
    // image to show depending on the transparency of those pixels.
    osg.setComposite(AlphaComposite.DstOver);
    osg.drawImage(cover, 0, 0, this);

    // And display this composited image on the screen. Note that the
    // image is opaque and that none of the screen background shows through
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("DST_OVER", 0, COVERHEIGHT + 15);

    // Now start over and do a new effect with the off-screen image.
    // First, fill the offscreen image with a new color gradient. We
    // don't care about the colors themselves; we just want the
    // translucency of the background to vary. We use opaque black to
    // transparent black. Note that since we've already used this offscreen
    // image, we set the composite to Src, we can fill the image and
    // ignore anything that is already there.
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now set the compositing type to SrcIn, so colors come from the
    // source, but translucency comes from the destination
    osg.setComposite(AlphaComposite.SrcIn);

    // Draw our loaded image into the off-screen image, compositing it.
    osg.drawImage(cover, 0, 0, this);

    // And then copy our off-screen image to the screen. Note that the
    // image is translucent and some of the image shows through.
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_IN", 0, COVERHEIGHT + 15);

    // If we do the same thing but use SrcOut, then the resulting image
    // will have the inverted translucency values of the destination
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);
    osg.setComposite(AlphaComposite.SrcOut);
    osg.drawImage(cover, 0, 0, this);
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_OUT", 0, COVERHEIGHT + 15);

    // Here's a cool effect; it has nothing to do with compositing, but
    // uses an arbitrary shape to clip the image. It uses Area to combine
    // shapes into more complicated ones.
    g.translate(COVERWIDTH + 10, 0);
    Shape savedClip = g.getClip(); // Save current clipping region
    // Create a shape to use as the new clipping region.
    // Begin with an ellipse
    Area clip = new Area(new Ellipse2D.Float(0, 0, COVERWIDTH, COVERHEIGHT));
    // Intersect with a rectangle, truncating the ellipse.
    clip.intersect(new Area(new Rectangle(5, 5, COVERWIDTH - 10, COVERHEIGHT - 10)));
    // Then subtract an ellipse from the bottom of the truncated ellipse.
    clip.subtract(new Area(new Ellipse2D.Float(COVERWIDTH / 2 - 40, COVERHEIGHT - 20, 80, 40)));
    // Use the resulting shape as the new clipping region
    g.clip(clip);
    // Then draw the image through this clipping region
    g.drawImage(cover, 0, 0, this);
    // Restore the old clipping region so we can label the effect
    g.setClip(savedClip);
    g.drawString("Clipping", 0, COVERHEIGHT + 15);
}

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

/**
 * Show the splash screen./* w  ww . ja  v  a2  s.  c  om*/
 */
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:nl.b3p.kaartenbalie.core.server.b3pLayering.ConfigLayer.java

protected void drawTitledMessageBox(Graphics2D g2d, String title, String message, int x, int y, int w, int h) {
    /* Do some calculations and init variables. */
    g2d.setFont(KBConfiguration.OHD_messageBoxFont);
    FontMetrics fm = g2d.getFontMetrics();
    int labelHeight = KBConfiguration.OHD_messageBoxFont.getSize() + (KBConfiguration.OHD_padding * 2);
    int angling = labelHeight;
    Rectangle2D testRectangle = fm.getStringBounds(title, g2d);
    int labelWidth = (int) testRectangle.getWidth();

    if (w < labelWidth + (2 * angling)) {
        w = labelWidth + (2 * angling);/*from  w  w  w . jav  a  2 s  . c  o  m*/
    }
    y += labelHeight;
    /* Now draw the box...    */
    drawMessageBox(g2d, message, x, y, w, h);

    /* Draw the label background */
    g2d.setColor(KBConfiguration.OHD_labelBoxColor);
    GeneralPath label = new GeneralPath();
    label.moveTo(x, y);
    label.lineTo(x + angling, y - labelHeight);
    label.lineTo(x + angling + labelWidth, y - labelHeight);
    label.lineTo(x + (angling * 2) + labelWidth, y);
    label.closePath();
    g2d.fill(label);

    /* Draw the label Lines..  */
    g2d.setColor(KBConfiguration.OHD_borderBoxTopLeft);
    g2d.drawLine(x, y, x + angling, y - labelHeight);
    g2d.drawLine(x + angling, y - labelHeight, x + angling + labelWidth, y - labelHeight);
    g2d.setColor(KBConfiguration.OHD_borderBoxBottomRight);
    g2d.drawLine(x + angling + labelWidth, y - labelHeight, x + (angling * 2) + labelWidth, y);
    g2d.setColor(KBConfiguration.OHD_borderBoxBackground);
    g2d.drawLine(x + (angling * 2) + labelWidth, y, x, y);
    /*Then add the title... */
    g2d.setColor(KBConfiguration.OHD_labelFontBoxColor);
    g2d.drawString(title, x + angling, y - KBConfiguration.OHD_padding);

}

From source file:edu.jhuapl.graphs.jfreechart.utils.CustomLabelNumberAxis.java

@Override
protected List<Tick> refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List<Tick> result = new ArrayList<Tick>();
    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);

    if (isAutoTickUnitSelection()) {
        selectAutoTickUnit(g2, dataArea, edge);
    }/*from  w ww  . j  a v  a 2 s . c  om*/

    TickUnit tu = getTickUnit();
    double size = tu.getSize();
    int count = this.tickCount != null ? this.tickCount : calculateVisibleTickCount();
    double lowestTickValue = this.lowestTickValue != null ? this.lowestTickValue
            : calculateLowestVisibleTickValue();

    if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
        int minorTickSpaces = getMinorTickCount();

        if (minorTickSpaces <= 0) {
            minorTickSpaces = tu.getMinorTickCount();
        }

        for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
            double minorTickValue = lowestTickValue - size * minorTick / minorTickSpaces;

            if (getRange().contains(minorTickValue)) {
                result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                        TextAnchor.CENTER, 0.0));
            }
        }

        for (int i = 0; i < count; i++) {
            double currentTickValue = lowestTickValue + (i * size);
            String tickLabel = tickValueToLabelMapping.get(currentTickValue);

            if (tickLabel == null) {
                NumberFormat formatter = getNumberFormatOverride();

                if (formatter != null) {
                    tickLabel = formatter.format(currentTickValue);
                } else {
                    tickLabel = getTickUnit().valueToString(currentTickValue);
                }
            }

            TextAnchor anchor = null;
            TextAnchor rotationAnchor = null;
            double angle = 0.0;

            if (isVerticalTickLabels()) {
                anchor = TextAnchor.CENTER_RIGHT;
                rotationAnchor = TextAnchor.CENTER_RIGHT;

                if (edge == RectangleEdge.TOP) {
                    angle = Math.PI / 2.0;
                } else {
                    angle = -Math.PI / 2.0;
                }
            } else {
                if (edge == RectangleEdge.TOP) {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                } else {
                    anchor = TextAnchor.TOP_CENTER;
                    rotationAnchor = TextAnchor.TOP_CENTER;
                }
            }

            Tick tick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle);
            result.add(tick);
            double nextTickValue = lowestTickValue + ((i + 1) * size);

            for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
                double minorTickValue = currentTickValue
                        + (nextTickValue - currentTickValue) * minorTick / minorTickSpaces;

                if (getRange().contains(minorTickValue)) {
                    result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                            TextAnchor.CENTER, 0.0));
                }
            }
        }
    }

    return result;
}

From source file:edu.jhuapl.graphs.jfreechart.utils.CustomLabelNumberAxis.java

@Override
protected List<Tick> refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List<Tick> result = new ArrayList<Tick>();
    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);

    if (isAutoTickUnitSelection()) {
        selectAutoTickUnit(g2, dataArea, edge);
    }/*from  w  w  w. j a va  2s . c o m*/

    TickUnit tu = getTickUnit();
    double size = tu.getSize();
    int count = this.tickCount != null ? this.tickCount : calculateVisibleTickCount();
    double lowestTickValue = this.lowestTickValue != null ? this.lowestTickValue
            : calculateLowestVisibleTickValue();

    if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
        int minorTickSpaces = getMinorTickCount();

        if (minorTickSpaces <= 0) {
            minorTickSpaces = tu.getMinorTickCount();
        }

        for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
            double minorTickValue = lowestTickValue - size * minorTick / minorTickSpaces;

            if (getRange().contains(minorTickValue)) {
                result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                        TextAnchor.CENTER, 0.0));
            }
        }

        for (int i = 0; i < count; i++) {
            double currentTickValue = lowestTickValue + (i * size);
            String tickLabel = tickValueToLabelMapping.get(currentTickValue);

            if (tickLabel == null) {
                NumberFormat formatter = getNumberFormatOverride();

                if (formatter != null) {
                    tickLabel = formatter.format(currentTickValue);
                } else {
                    tickLabel = getTickUnit().valueToString(currentTickValue);
                }
            }

            TextAnchor anchor = null;
            TextAnchor rotationAnchor = null;
            double angle = 0.0;

            if (isVerticalTickLabels()) {
                if (edge == RectangleEdge.LEFT) {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    angle = -Math.PI / 2.0;
                } else {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    angle = Math.PI / 2.0;
                }
            } else {
                if (edge == RectangleEdge.LEFT) {
                    anchor = TextAnchor.CENTER_RIGHT;
                    rotationAnchor = TextAnchor.CENTER_RIGHT;
                } else {
                    anchor = TextAnchor.CENTER_LEFT;
                    rotationAnchor = TextAnchor.CENTER_LEFT;
                }
            }

            Tick tick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle);
            result.add(tick);
            double nextTickValue = lowestTickValue + ((i + 1) * size);

            for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
                double minorTickValue = currentTickValue
                        + (nextTickValue - currentTickValue) * minorTick / minorTickSpaces;

                if (getRange().contains(minorTickValue)) {
                    result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                            TextAnchor.CENTER, 0.0));
                }
            }
        }
    }

    return result;
}

From source file:edu.csudh.goTorosBank.WithdrawServlet.java

public String writeIntoCheck(String filePath, String username, String theAmount, String amountInWords,
        String dateWrote, String person_payingto, String billType) throws IOException, NullPointerException {

    File blueCheck = new File("blank-blue-check.jpg");
    String pathToOriginal = getServletContext().getRealPath("/" + blueCheck);

    File file = new File(pathToOriginal);
    BufferedImage imageToCopy = null;
    try {/* w w w.  j a  v  a  2 s .  c om*/
        imageToCopy = ImageIO.read(file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String amount = theAmount;
    String person_gettingPayed = person_payingto;
    String amountinWords = amountInWords;
    String date = dateWrote;
    String bill_type = billType;

    int w = imageToCopy.getWidth();
    int h = imageToCopy.getHeight();
    BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();
    g2d.setColor(g2d.getBackground());
    g2d.fillRect(0, 0, w, h);
    g2d.drawImage(imageToCopy, 0, -100, null);
    g2d.setPaint(Color.black);
    g2d.setFont(new java.awt.Font("Serif", Font.BOLD, 36));
    //g2d.setFont(new Font("Serif", Font.BOLD, 36));

    FontMetrics fm = g2d.getFontMetrics();
    int x = img.getWidth() - fm.stringWidth(amount) - 100;
    int y = fm.getHeight();
    g2d.drawString(amount, x - 70, y + 335);
    g2d.drawString(person_gettingPayed, x - 800, y + 329);
    g2d.drawString(amountinWords, x - 940, y + 390);
    g2d.drawString(date, x - 340, y + 245);
    g2d.drawString(bill_type, x - 900, y + 530);

    String signature = "Use The Force";
    g2d.setFont(new java.awt.Font("Monotype Corsiva", Font.BOLD | Font.ITALIC, 36));
    g2d.drawString(signature, x - 340, y + 530);
    g2d.dispose();
    /*write check to file*/
    String filename = fileNameGenerator(username);
    String fullname = filePath + "_" + filename + ".jpg";
    ImageIO.write(img, "jpg", new File(fullname));
    return fullname;
}

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

private void renderLegend(Graphics2D g2) {
    g2.setFont(NORMALFONT.deriveFont(32f).deriveFont(Font.BOLD));

    // erst die Breite der Zahlen fuer die Einrueckung berechnen
    Font font = g2.getFont();/*  w w  w.j av  a  2 s.co m*/
    FontRenderContext fontRenderContext = g2.getFontRenderContext();
    Map<Segment, Double> numberWidths = new HashMap<>();
    double maxNumberWidth = 0;
    for (Segment seg : segments) {
        double numberWidth = font
                .getStringBounds(legendPortionFormat.format(seg.getPortion()), fontRenderContext).getWidth();
        numberWidths.put(seg, numberWidth);
        maxNumberWidth = Math.max(maxNumberWidth, numberWidth);
    }
    if (showTotalInLegend) {
        double numberWidth = font.getStringBounds(legendPortionFormat.format(total), fontRenderContext)
                .getWidth();
        numberWidths.put(null, numberWidth);
        maxNumberWidth = Math.max(maxNumberWidth, numberWidth);
    }

    // jetzt die Zeilen in die Legende malen
    int verticalOffset = 0;
    for (int row = 0; row < segments.size(); ++row) {
        Segment seg = getLegendSegment(row);
        // Zahlen rechtsbuendig
        double indentation = maxNumberWidth - numberWidths.get(seg);
        String segmentPortionNumber = legendPortionFormat.format(seg.getPortion());
        String segmentText = seg.getText();
        Color segmentColor = seg.getColor();
        String subSegmentText = seg.getSubSegmentText();
        String subNumberText = legendPortionFormat.format(seg.subPortion);
        drawLegendLine(g2, verticalOffset, indentation, segmentColor, segmentText, segmentPortionNumber,
                seg.getPortion() != 1d, seg.getSubPortion() > 0, subSegmentText, subNumberText,
                seg.getSubPortion() != 1d);
        verticalOffset += 85;
    }
    if (showTotalInLegend) {
        double indentation = maxNumberWidth - numberWidths.get(null);
        String subNumberText = legendPortionFormat.format(subTotal);
        drawLegendLine(g2, verticalOffset, indentation, null, totalText, legendPortionFormat.format(total),
                total != 1, subTotalTextOrNull != null, subTotalTextOrNull, subNumberText, subTotal != 1);
    }
}

From source file:TextBouncer.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    setAntialiasing(g2);//w  w w  .  jav a 2 s .c  o  m
    setTransform(g2);
    setPaint(g2);
    // Draw the string.
    g2.setFont(getFont());
    g2.drawString(mString, mX, mY + mHeight);
    drawAxes(g2);
}