Java Code Examples for java.awt.Graphics2D#getFontMetrics()

The following examples show how to use java.awt.Graphics2D#getFontMetrics() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AvatarLoader.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
private static AvatarImg fallback(String letter, Color color, int size) {
    BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);

    Graphics2D graphics = img.createGraphics();
    graphics.setColor(color);
    graphics.fillRect(0, 0, size, size);

    graphics.setFont(new Font(Font.DIALOG, Font.PLAIN, size));
    graphics.setColor(LETTER_COLOR);
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

    FontMetrics fm = graphics.getFontMetrics();
    Rectangle2D r = fm.getStringBounds(letter, graphics);

    graphics.drawString(letter,
            (size - (int) r.getWidth()) / 2.0f,
            // adjust to font baseline
            // Note: not centered for letters with descent (drawing under
            // the baseline), dont know how to get that
            (size - (int) r.getHeight()) / 2.0f + fm.getAscent());

    return new AvatarImg(img, true);
}
 
Example 2
Source File: Axis.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Update lable gap
 *
 * @param g Graphics2D
 * @param rect The rectangle
 */
public void updateLabelGap(Graphics2D g, Rectangle2D rect) {
    if (this.getTickValues() == null) {
        return;
    }

    double len;
    int n = this.getTickValues().length;
    int nn;
    if (this.xAxis) {
        len = rect.getWidth();
        int labLen = this.getMaxLabelLength(g);
        nn = (int) ((len * 0.8) / labLen);
    } else {
        len = rect.getHeight();
        FontMetrics metrics = g.getFontMetrics(this.label.getFont());
        nn = (int) (len / metrics.getHeight());
    }
    if (nn == 0) {
        nn = 1;
    }
    this.tickLabelGap = n / nn + 1;
}
 
Example 3
Source File: EquationDisplay.java    From filthy-rich-clients with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void drawAxis(Graphics2D g2) {
    double axisH = yPositionToPixel(originY);
    double axisV = xPositionToPixel(originX);
    
    g2.setColor(COLOR_AXIS);
    Stroke stroke = g2.getStroke();
    g2.setStroke(new BasicStroke(STROKE_AXIS));
    
    g2.drawLine(0, (int) axisH, getWidth(), (int) axisH);
    g2.drawLine((int) axisV, 0, (int) axisV, getHeight());
    
    FontMetrics metrics = g2.getFontMetrics();
    g2.drawString(formatter.format(0.0), (int) axisV + 5, (int) axisH + metrics.getHeight());
    
    g2.setStroke(stroke);
}
 
Example 4
Source File: Chart_26_Axis_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Returns a rectangle that encloses the axis label.  This is typically 
 * used for layout purposes (it gives the maximum dimensions of the label).
 *
 * @param g2  the graphics device.
 * @param edge  the edge of the plot area along which the axis is measuring.
 *
 * @return The enclosing rectangle.
 */
protected Rectangle2D getLabelEnclosure(Graphics2D g2, RectangleEdge edge) {

    Rectangle2D result = new Rectangle2D.Double();
    String axisLabel = getLabel();
    if (axisLabel != null && !axisLabel.equals("")) {
        FontMetrics fm = g2.getFontMetrics(getLabelFont());
        Rectangle2D bounds = TextUtilities.getTextBounds(axisLabel, g2, fm);
        RectangleInsets insets = getLabelInsets();
        bounds = insets.createOutsetRectangle(bounds);
        double angle = getLabelAngle();
        if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) {
            angle = angle - Math.PI / 2.0;
        }
        double x = bounds.getCenterX();
        double y = bounds.getCenterY();
        AffineTransform transformer 
            = AffineTransform.getRotateInstance(angle, x, y);
        Shape labelBounds = transformer.createTransformedShape(bounds);
        result = labelBounds.getBounds2D();
    }

    return result;

}
 
Example 5
Source File: MarkerAxisBand.java    From openstock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * A utility method that draws a string inside a rectangle.
 *
 * @param g2  the graphics device.
 * @param bounds  the rectangle.
 * @param font  the font.
 * @param text  the text.
 */
private void drawStringInRect(Graphics2D g2, Rectangle2D bounds, Font font,
                              String text) {

    g2.setFont(font);
    FontMetrics fm = g2.getFontMetrics(font);
    Rectangle2D r = TextUtilities.getTextBounds(text, g2, fm);
    double x = bounds.getX();
    if (r.getWidth() < bounds.getWidth()) {
        x = x + (bounds.getWidth() - r.getWidth()) / 2;
    }
    LineMetrics metrics = font.getLineMetrics(
        text, g2.getFontRenderContext()
    );
    g2.drawString(
        text, (float) x, (float) (bounds.getMaxY()
            - this.bottomInnerGap - metrics.getDescent())
    );
}
 
Example 6
Source File: Axis.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a rectangle that encloses the axis label.  This is typically
 * used for layout purposes (it gives the maximum dimensions of the label).
 *
 * @param g2  the graphics device.
 * @param edge  the edge of the plot area along which the axis is measuring.
 *
 * @return The enclosing rectangle.
 */
protected Rectangle2D getLabelEnclosure(Graphics2D g2, RectangleEdge edge) {

    Rectangle2D result = new Rectangle2D.Double();
    String axisLabel = getLabel();
    if (axisLabel != null && !axisLabel.equals("")) {
        FontMetrics fm = g2.getFontMetrics(getLabelFont());
        Rectangle2D bounds = TextUtilities.getTextBounds(axisLabel, g2, fm);
        RectangleInsets insets = getLabelInsets();
        bounds = insets.createOutsetRectangle(bounds);
        double angle = getLabelAngle();
        if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) {
            angle = angle - Math.PI / 2.0;
        }
        double x = bounds.getCenterX();
        double y = bounds.getCenterY();
        AffineTransform transformer
            = AffineTransform.getRotateInstance(angle, x, y);
        Shape labelBounds = transformer.createTransformedShape(bounds);
        result = labelBounds.getBounds2D();
    }

    return result;

}
 
Example 7
Source File: Axis.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a rectangle that encloses the axis label.  This is typically 
 * used for layout purposes (it gives the maximum dimensions of the label).
 *
 * @param g2  the graphics device.
 * @param edge  the edge of the plot area along which the axis is measuring.
 *
 * @return The enclosing rectangle.
 */
protected Rectangle2D getLabelEnclosure(Graphics2D g2, RectangleEdge edge) {

    Rectangle2D result = new Rectangle2D.Double();
    String axisLabel = getLabel();
    if (axisLabel != null && !axisLabel.equals("")) {
        FontMetrics fm = g2.getFontMetrics(getLabelFont());
        Rectangle2D bounds = TextUtilities.getTextBounds(axisLabel, g2, fm);
        RectangleInsets insets = getLabelInsets();
        bounds = insets.createOutsetRectangle(bounds);
        double angle = getLabelAngle();
        if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) {
            angle = angle - Math.PI / 2.0;
        }
        double x = bounds.getCenterX();
        double y = bounds.getCenterY();
        AffineTransform transformer 
            = AffineTransform.getRotateInstance(angle, x, y);
        Shape labelBounds = transformer.createTransformedShape(bounds);
        result = labelBounds.getBounds2D();
    }

    return result;

}
 
Example 8
Source File: ValueAxis.java    From SIMVA-SoS with Apache License 2.0 5 votes vote down vote up
/**
 * A utility method for determining the width of the widest tick label.
 *
 * @param ticks  the ticks.
 * @param g2  the graphics device.
 * @param drawArea  the area within which the plot and axes should be drawn.
 * @param vertical  a flag that indicates whether or not the tick labels
 *                  are 'vertical'.
 *
 * @return The width of the tallest tick label.
 */
protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2,
        Rectangle2D drawArea, boolean vertical) {

    RectangleInsets insets = getTickLabelInsets();
    Font font = getTickLabelFont();
    double maxWidth = 0.0;
    if (!vertical) {
        FontMetrics fm = g2.getFontMetrics(font);
        Iterator iterator = ticks.iterator();
        while (iterator.hasNext()) {
            Tick tick = (Tick) iterator.next();
            Rectangle2D labelBounds = null;
            if (tick instanceof LogTick) {
                LogTick lt = (LogTick) tick;
                if (lt.getAttributedLabel() != null) {
                    labelBounds = AttrStringUtils.getTextBounds(
                            lt.getAttributedLabel(), g2);
                }
            } else if (tick.getText() != null) {
                labelBounds = TextUtilities.getTextBounds(tick.getText(), 
                        g2, fm);
            }
            if (labelBounds != null 
                    && labelBounds.getWidth() + insets.getLeft()
                    + insets.getRight() > maxWidth) {
                maxWidth = labelBounds.getWidth()
                           + insets.getLeft() + insets.getRight();
            }
        }
    } else {
        LineMetrics metrics = font.getLineMetrics("ABCxyz",
                g2.getFontRenderContext());
        maxWidth = metrics.getHeight()
                   + insets.getTop() + insets.getBottom();
    }
    return maxWidth;

}
 
Example 9
Source File: VectorGraphics2D.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
public FontMetrics getFontMetrics(Font f) {
	// This one stumped me; I'm not sure how we're supposed to handle this?
	BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
	Graphics2D g = bi.createGraphics();
	context.install(g);
	FontMetrics returnValue = g.getFontMetrics(f);
	g.dispose();
	return returnValue;
}
 
Example 10
Source File: ScreenshotOverlay.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Dimension render(Graphics2D graphics)
{
	if (consumers.isEmpty())
	{
		return null;
	}

	final MainBufferProvider bufferProvider = (MainBufferProvider) client.getBufferProvider();
	final int imageHeight = ((BufferedImage) bufferProvider.getImage()).getHeight();
	final int y = imageHeight - plugin.getReportButton().getHeight() - 1;

	graphics.drawImage(plugin.getReportButton(), REPORT_BUTTON_X_OFFSET, y, null);

	graphics.setFont(FontManager.getRunescapeSmallFont());
	FontMetrics fontMetrics = graphics.getFontMetrics();

	String date = DATE_FORMAT.format(new Date());
	final int dateWidth = fontMetrics.stringWidth(date);
	final int dateHeight = fontMetrics.getHeight();

	final int textX = REPORT_BUTTON_X_OFFSET + plugin.getReportButton().getWidth() / 2 - dateWidth / 2;
	final int textY = y + plugin.getReportButton().getHeight() / 2 + dateHeight / 2;

	graphics.setColor(Color.BLACK);
	graphics.drawString(date, textX + 1, textY + 1);

	graphics.setColor(Color.WHITE);
	graphics.drawString(date, textX, textY);

	// Request the queued screenshots to be taken,
	// now that the timestamp is visible.
	Consumer<Image> consumer;
	while ((consumer = consumers.poll()) != null)
	{
		drawManager.requestNextFrameListener(consumer);
	}

	return null;
}
 
Example 11
Source File: YAxisImpl.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** @param gc
 *  @param screen_y Screen location of label along the axis
 *  @param mark Label text
 *  @param floating Add 'floating' box?
 *  @param avoid Outline of previous label to avoid
 *  @return Outline of this label or the last one if skipping this label
 */
private Rectangle drawTickLabel(final Graphics2D gc, final int screen_y, final String mark, final boolean floating, final Rectangle avoid)
{
    final Rectangle region = getBounds();
    gc.setFont(scale_font);
    final FontMetrics metrics = gc.getFontMetrics();
    final int mark_height = metrics.stringWidth(mark);
    final int mark_width = metrics.getHeight();
    final int x = is_right ? region.x + TICK_LENGTH : region.x + region.width - TICK_LENGTH - mark_width;
    int y = screen_y  - mark_height/2;
    // Correct location of top label to remain within region
    if (y < 0)
        y = 0;

    final Rectangle outline = new Rectangle(x-BORDER,  y-BORDER, mark_width+2*BORDER, mark_height+2*BORDER);
    if (floating)
    {
        if (is_right)
            gc.drawLine(x - TICK_LENGTH, screen_y, x, screen_y);
        else
            gc.drawLine(x + mark_width, screen_y, x + mark_width + TICK_LENGTH, screen_y);

        // Box around label
        gc.clearRect(outline.x, outline.y, outline.width, outline.height);
        gc.drawRect(outline.x, outline.y, outline.width, outline.height);
    }

    if (avoid != null  &&  outline.intersects(avoid))
        return avoid;
    // Debug: Outline of text
    // gc.drawRect(x,  y, mark_width, mark_height); // Debug outline of tick label
    GraphicsUtils.drawVerticalText(gc, x, y, mark, !is_right);
    return outline;
}
 
Example 12
Source File: ValueAxis.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A utility method for determining the height of the tallest tick label.
 *
 * @param ticks  the ticks.
 * @param g2  the graphics device.
 * @param drawArea  the area within which the plot and axes should be drawn.
 * @param vertical  a flag that indicates whether or not the tick labels
 *                  are 'vertical'.
 *
 * @return The height of the tallest tick label.
 */
protected double findMaximumTickLabelHeight(List ticks, Graphics2D g2,
        Rectangle2D drawArea, boolean vertical) {

    RectangleInsets insets = getTickLabelInsets();
    Font font = getTickLabelFont();
    g2.setFont(font);
    double maxHeight = 0.0;
    if (vertical) {
        FontMetrics fm = g2.getFontMetrics(font);
        Iterator iterator = ticks.iterator();
        while (iterator.hasNext()) {
            Tick tick = (Tick) iterator.next();
            Rectangle2D labelBounds = null;
            if (tick instanceof LogTick) {
                LogTick lt = (LogTick) tick;
                if (lt.getAttributedLabel() != null) {
                    labelBounds = AttrStringUtils.getTextBounds(
                            lt.getAttributedLabel(), g2);
                }
            } else if (tick.getText() != null) {
                labelBounds = TextUtilities.getTextBounds(
                        tick.getText(), g2, fm);
            }
            if (labelBounds != null && labelBounds.getWidth() 
                    + insets.getTop() + insets.getBottom() > maxHeight) {
                maxHeight = labelBounds.getWidth()
                            + insets.getTop() + insets.getBottom();
            }
        }
    } else {
        LineMetrics metrics = font.getLineMetrics("ABCxyz",
                g2.getFontRenderContext());
        maxHeight = metrics.getHeight()
                    + insets.getTop() + insets.getBottom();
    }
    return maxHeight;

}
 
Example 13
Source File: WidgetOverlay.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
private void renderWidgetOverlay(Graphics2D graphics, Portal portal, String text, Color color)
{
	Widget shield = client.getWidget(portal.getWidget().getShield());
	Widget icon = client.getWidget(portal.getWidget().getIcon());
	Widget hp = client.getWidget(portal.getWidget().getHitpoints());

	Widget bar = client.getWidget(WidgetInfo.PEST_CONTROL_ACTIVITY_BAR).getChild(0);

	Rectangle2D barBounds = bar.getBounds().getBounds2D();

	// create one rectangle from two different widget bounds
	Rectangle2D bounds = union(shield.getBounds().getBounds2D(), icon.getBounds().getBounds2D());
	bounds = union(bounds, hp.getBounds().getBounds2D());

	graphics.setColor(color);
	graphics.draw(new Rectangle2D.Double(bounds.getX(), bounds.getY() - 2, bounds.getWidth(), bounds.getHeight() - 3));

	FontMetrics fm = graphics.getFontMetrics();
	Rectangle2D textBounds = fm.getStringBounds(text, graphics);
	int x = (int) (bounds.getX() + (bounds.getWidth() / 2) - (textBounds.getWidth() / 2));
	int y = (int) (bounds.getY() + bounds.getHeight() + textBounds.getHeight() + barBounds.getHeight());

	graphics.setColor(Color.BLACK);
	graphics.drawString(text, x + 1, y + 5);
	graphics.setColor(color);
	graphics.drawString(text, x, y + 4);
}
 
Example 14
Source File: NumberAxis.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified
 * tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we
 * just look at two values: the lower bound and the upper bound for the
 * axis.  These two values will usually be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return The estimated maximum width of the tick labels.
 */
protected double estimateMaximumTickLabelWidth(Graphics2D g2,
                                               TickUnit unit) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();

    if (isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of the
        // font)...
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc);
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
        Range range = getRange();
        double lower = range.getLowerBound();
        double upper = range.getUpperBound();
        String lowerStr, upperStr;
        NumberFormat formatter = getNumberFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.valueToString(lower);
            upperStr = unit.valueToString(upper);
        }
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example 15
Source File: PiePlot.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Draws the pie section labels in the simple form.
 * 
 * @param g2  the graphics device.
 * @param keys  the section keys.
 * @param totalValue  the total value for all sections in the pie.
 * @param plotArea  the plot area.
 * @param pieArea  the area containing the pie.
 * @param state  the plot state.
 *
 * @since 1.0.7
 */
protected void drawSimpleLabels(Graphics2D g2, List keys, 
        double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, 
        PiePlotState state) {
    
    Composite originalComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 
            1.0f));

    RectangleInsets labelInsets = new RectangleInsets(UnitType.RELATIVE, 
            0.18, 0.18, 0.18, 0.18);
    Rectangle2D labelsArea = labelInsets.createInsetRectangle(pieArea);
    double runningTotal = 0.0;
    Iterator iterator = keys.iterator();
    while (iterator.hasNext()) {
        Comparable key = (Comparable) iterator.next();
        boolean include = true;
        double v = 0.0;
        Number n = getDataset().getValue(key);
        if (n == null) {
            include = !getIgnoreNullValues();
        }
        else {
            v = n.doubleValue();
            include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
        }

        if (include) {
            runningTotal = runningTotal + v;
            // work out the mid angle (0 - 90 and 270 - 360) = right, 
            // otherwise left
            double mid = getStartAngle() + (getDirection().getFactor()
                    * ((runningTotal - v / 2.0) * 360) / totalValue);
            
            Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), 
                    mid - getStartAngle(), Arc2D.OPEN);
            int x = (int) arc.getEndPoint().getX();
            int y = (int) arc.getEndPoint().getY();
            
            PieSectionLabelGenerator labelGenerator = getLabelGenerator();
            if (labelGenerator == null) {
                continue;
            }
            String label = labelGenerator.generateSectionLabel(
                    this.dataset, key);
            if (label == null) {
                continue;
            }
            g2.setFont(this.labelFont);
            FontMetrics fm = g2.getFontMetrics();
            Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
            Rectangle2D out = this.labelPadding.createOutsetRectangle(
                    bounds);
            Shape bg = ShapeUtilities.createTranslatedShape(out, 
                    x - bounds.getCenterX(), y - bounds.getCenterY());
            if (this.labelShadowPaint != null) {
                Shape shadow = ShapeUtilities.createTranslatedShape(bg, 
                        this.shadowXOffset, this.shadowYOffset);
                g2.setPaint(this.labelShadowPaint);
                g2.fill(shadow);
            }
            if (this.labelBackgroundPaint != null) {
                g2.setPaint(this.labelBackgroundPaint);
                g2.fill(bg);
            }
            if (this.labelOutlinePaint != null 
                    && this.labelOutlineStroke != null) {
                g2.setPaint(this.labelOutlinePaint);
                g2.setStroke(this.labelOutlineStroke);
                g2.draw(bg);
            }
            
            g2.setPaint(this.labelPaint);
            g2.setFont(this.labelFont);
            TextUtilities.drawAlignedString(getLabelGenerator()
                    .generateSectionLabel(getDataset(), key), g2, x, y, 
                    TextAnchor.CENTER);
            
        }
    }
   
    g2.setComposite(originalComposite);

}
 
Example 16
Source File: DialValueIndicator.java    From ECG-Viewer with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Draws the background to the specified graphics device.  If the dial
 * frame specifies a window, the clipping region will already have been
 * set to this window before this method is called.
 *
 * @param g2  the graphics device (<code>null</code> not permitted).
 * @param plot  the plot (ignored here).
 * @param frame  the dial frame (ignored here).
 * @param view  the view rectangle (<code>null</code> not permitted).
 */
@Override
public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame,
        Rectangle2D view) {

    // work out the anchor point
    Rectangle2D f = DialPlot.rectangleByRadius(frame, this.radius,
            this.radius);
    Arc2D arc = new Arc2D.Double(f, this.angle, 0.0, Arc2D.OPEN);
    Point2D pt = arc.getStartPoint();

    // the indicator bounds is calculated from the templateValue (which
    // determines the minimum size), the maxTemplateValue (which, if
    // specified, provides a maximum size) and the actual value
    FontMetrics fm = g2.getFontMetrics(this.font);
    double value = plot.getValue(this.datasetIndex);
    String valueStr = this.formatter.format(value);
    Rectangle2D valueBounds = TextUtilities.getTextBounds(valueStr, g2, fm);

    // calculate the bounds of the template value
    String s = this.formatter.format(this.templateValue);
    Rectangle2D tb = TextUtilities.getTextBounds(s, g2, fm);
    double minW = tb.getWidth();
    double minH = tb.getHeight();

    double maxW = Double.MAX_VALUE;
    double maxH = Double.MAX_VALUE;
    if (this.maxTemplateValue != null) {
        s = this.formatter.format(this.maxTemplateValue);
        tb = TextUtilities.getTextBounds(s, g2, fm);
        maxW = Math.max(tb.getWidth(), minW);
        maxH = Math.max(tb.getHeight(), minH);
    }
    double w = fixToRange(valueBounds.getWidth(), minW, maxW);
    double h = fixToRange(valueBounds.getHeight(), minH, maxH);

    // align this rectangle to the frameAnchor
    Rectangle2D bounds = RectangleAnchor.createRectangle(new Size2D(w, h),
            pt.getX(), pt.getY(), this.frameAnchor);

    // add the insets
    Rectangle2D fb = this.insets.createOutsetRectangle(bounds);

    // draw the background
    g2.setPaint(this.backgroundPaint);
    g2.fill(fb);

    // draw the border
    g2.setStroke(this.outlineStroke);
    g2.setPaint(this.outlinePaint);
    g2.draw(fb);

    // now find the text anchor point
    Shape savedClip = g2.getClip();
    g2.clip(fb);

    Point2D pt2 = RectangleAnchor.coordinates(bounds, this.valueAnchor);
    g2.setPaint(this.paint);
    g2.setFont(this.font);
    TextUtilities.drawAlignedString(valueStr, g2, (float) pt2.getX(),
            (float) pt2.getY(), this.textAnchor);
    g2.setClip(savedClip);

}
 
Example 17
Source File: Regression_142687_swing.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Presents the Exceptions if the chart cannot be displayed properly.
 * 
 * @param g2d
 * @param ex
 */
private final void showException( Graphics2D g2d, Exception ex )
{
	String sWrappedException = ex.getClass( ).getName( );
	Throwable th = ex;
	while ( ex.getCause( ) != null )
	{
		ex = (Exception) ex.getCause( );
	}
	String sException = ex.getClass( ).getName( );
	if ( sWrappedException.equals( sException ) )
	{
		sWrappedException = null;
	}

	String sMessage = null;
	if ( th instanceof BirtException )
	{
		sMessage = ( (BirtException) th ).getLocalizedMessage( );
	}
	else
	{
		sMessage = ex.getMessage( );
	}

	if ( sMessage == null )
	{
		sMessage = "<null>";//$NON-NLS-1$
	}

	StackTraceElement[] stea = ex.getStackTrace( );
	Dimension d = getSize( );

	Font fo = new Font( "Monospaced", Font.BOLD, 14 );//$NON-NLS-1$
	g2d.setFont( fo );
	FontMetrics fm = g2d.getFontMetrics( );
	g2d.setColor( Color.WHITE );
	g2d.fillRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setColor( Color.BLACK );
	g2d.drawRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setClip( 20, 20, d.width - 40, d.height - 40 );
	int x = 25, y = 20 + fm.getHeight( );
	g2d.drawString( "Exception:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Exception:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.RED );
	g2d.drawString( sException, x, y );
	x = 25;
	y += fm.getHeight( );
	if ( sWrappedException != null )
	{
		g2d.setColor( Color.BLACK );
		g2d.drawString( "Wrapped In:", x, y );//$NON-NLS-1$
		x += fm.stringWidth( "Wrapped In:" ) + 5;//$NON-NLS-1$
		g2d.setColor( Color.RED );
		g2d.drawString( sWrappedException, x, y );
		x = 25;
		y += fm.getHeight( );
	}
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Message:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Message:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.BLUE );
	g2d.drawString( sMessage, x, y );
	x = 25;
	y += fm.getHeight( );
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Trace:", x, y );//$NON-NLS-1$
	x = 40;
	y += fm.getHeight( );
	g2d.setColor( Color.GREEN.darker( ) );
	for ( int i = 0; i < stea.length; i++ )
	{
		g2d.drawString( stea[i].getClassName( ) + ":"//$NON-NLS-1$
				+ stea[i].getMethodName( ) + "(...):"//$NON-NLS-1$
				+ stea[i].getLineNumber( ), x, y );
		x = 40;
		y += fm.getHeight( );
	}
}
 
Example 18
Source File: Regression_116630_swing.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Presents the Exceptions if the chart cannot be displayed properly.
 * 
 * @param g2d
 * @param ex
 */
private final void showException( Graphics2D g2d, Exception ex )
{
	String sWrappedException = ex.getClass( ).getName( );
	Throwable th = ex;
	while ( ex.getCause( ) != null )
	{
		ex = (Exception) ex.getCause( );
	}
	String sException = ex.getClass( ).getName( );
	if ( sWrappedException.equals( sException ) )
	{
		sWrappedException = null;
	}

	String sMessage = null;
	if ( th instanceof BirtException )
	{
		sMessage = ( (BirtException) th ).getLocalizedMessage( );
	}
	else
	{
		sMessage = ex.getMessage( );
	}

	if ( sMessage == null )
	{
		sMessage = "<null>";//$NON-NLS-1$
	}

	StackTraceElement[] stea = ex.getStackTrace( );
	Dimension d = getSize( );

	Font fo = new Font( "Monospaced", Font.BOLD, 14 );//$NON-NLS-1$
	g2d.setFont( fo );
	FontMetrics fm = g2d.getFontMetrics( );
	g2d.setColor( Color.WHITE );
	g2d.fillRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setColor( Color.BLACK );
	g2d.drawRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setClip( 20, 20, d.width - 40, d.height - 40 );
	int x = 25, y = 20 + fm.getHeight( );
	g2d.drawString( "Exception:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Exception:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.RED );
	g2d.drawString( sException, x, y );
	x = 25;
	y += fm.getHeight( );
	if ( sWrappedException != null )
	{
		g2d.setColor( Color.BLACK );
		g2d.drawString( "Wrapped In:", x, y );//$NON-NLS-1$
		x += fm.stringWidth( "Wrapped In:" ) + 5;//$NON-NLS-1$
		g2d.setColor( Color.RED );
		g2d.drawString( sWrappedException, x, y );
		x = 25;
		y += fm.getHeight( );
	}
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Message:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Message:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.BLUE );
	g2d.drawString( sMessage, x, y );
	x = 25;
	y += fm.getHeight( );
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Trace:", x, y );//$NON-NLS-1$
	x = 40;
	y += fm.getHeight( );
	g2d.setColor( Color.GREEN.darker( ) );
	for ( int i = 0; i < stea.length; i++ )
	{
		g2d.drawString( stea[i].getClassName( ) + ":"//$NON-NLS-1$
				+ stea[i].getMethodName( ) + "(...):"//$NON-NLS-1$
				+ stea[i].getLineNumber( ), x, y );
		x = 40;
		y += fm.getHeight( );
	}
}
 
Example 19
Source File: SwingToggleVisibilityViewer.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Presents the Exceptions if the chart cannot be displayed properly.
 * 
 * @param g2d
 * @param ex
 */
private final void showException( Graphics2D g2d, Exception ex )
{
	String sWrappedException = ex.getClass( ).getName( );
	Throwable th = ex;
	while ( ex.getCause( ) != null )
	{
		ex = (Exception) ex.getCause( );
	}
	String sException = ex.getClass( ).getName( );
	if ( sWrappedException.equals( sException ) )
	{
		sWrappedException = null;
	}

	String sMessage = null;
	if ( th instanceof BirtException )
	{
		sMessage = ( (BirtException) th ).getLocalizedMessage( );
	}
	else
	{
		sMessage = ex.getMessage( );
	}

	if ( sMessage == null )
	{
		sMessage = "<null>";//$NON-NLS-1$
	}

	StackTraceElement[] stea = ex.getStackTrace( );
	Dimension d = getSize( );

	Font fo = new Font( "Monospaced", Font.BOLD, 14 );//$NON-NLS-1$
	g2d.setFont( fo );
	FontMetrics fm = g2d.getFontMetrics( );
	g2d.setColor( Color.WHITE );
	g2d.fillRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setColor( Color.BLACK );
	g2d.drawRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setClip( 20, 20, d.width - 40, d.height - 40 );
	int x = 25, y = 20 + fm.getHeight( );
	g2d.drawString( "Exception:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Exception:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.RED );
	g2d.drawString( sException, x, y );
	x = 25;
	y += fm.getHeight( );
	if ( sWrappedException != null )
	{
		g2d.setColor( Color.BLACK );
		g2d.drawString( "Wrapped In:", x, y );//$NON-NLS-1$
		x += fm.stringWidth( "Wrapped In:" ) + 5;//$NON-NLS-1$
		g2d.setColor( Color.RED );
		g2d.drawString( sWrappedException, x, y );
		x = 25;
		y += fm.getHeight( );
	}
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Message:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Message:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.BLUE );
	g2d.drawString( sMessage, x, y );
	x = 25;
	y += fm.getHeight( );
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Trace:", x, y );//$NON-NLS-1$
	x = 40;
	y += fm.getHeight( );
	g2d.setColor( Color.GREEN.darker( ) );
	for ( int i = 0; i < stea.length; i++ )
	{
		g2d.drawString( stea[i].getClassName( ) + ":"//$NON-NLS-1$
				+ stea[i].getMethodName( ) + "(...):"//$NON-NLS-1$
				+ stea[i].getLineNumber( ), x, y );
		x = 40;
		y += fm.getHeight( );
	}
}
 
Example 20
Source File: PeriodAxis.java    From ccu-historian with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Estimates the space (height or width) required to draw the axis.
 *
 * @param g2  the graphics device.
 * @param plot  the plot that the axis belongs to.
 * @param plotArea  the area within which the plot (including axes) should
 *                  be drawn.
 * @param edge  the axis location.
 * @param space  space already reserved.
 *
 * @return The space required to draw the axis (including pre-reserved
 *         space).
 */
@Override
public AxisSpace reserveSpace(Graphics2D g2, Plot plot, 
        Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {
    // create a new space object if one wasn't supplied...
    if (space == null) {
        space = new AxisSpace();
    }

    // if the axis is not visible, no additional space is required...
    if (!isVisible()) {
        return space;
    }

    // if the axis has a fixed dimension, return it...
    double dimension = getFixedDimension();
    if (dimension > 0.0) {
        space.ensureAtLeast(dimension, edge);
    }

    // get the axis label size and update the space object...
    Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);
    double labelHeight, labelWidth;
    double tickLabelBandsDimension = 0.0;

    for (int i = 0; i < this.labelInfo.length; i++) {
        PeriodAxisLabelInfo info = this.labelInfo[i];
        FontMetrics fm = g2.getFontMetrics(info.getLabelFont());
        tickLabelBandsDimension
            += info.getPadding().extendHeight(fm.getHeight());
    }

    if (RectangleEdge.isTopOrBottom(edge)) {
        labelHeight = labelEnclosure.getHeight();
        space.add(labelHeight + tickLabelBandsDimension, edge);
    }
    else if (RectangleEdge.isLeftOrRight(edge)) {
        labelWidth = labelEnclosure.getWidth();
        space.add(labelWidth + tickLabelBandsDimension, edge);
    }

    // add space for the outer tick labels, if any...
    double tickMarkSpace = 0.0;
    if (isTickMarksVisible()) {
        tickMarkSpace = getTickMarkOutsideLength();
    }
    if (this.minorTickMarksVisible) {
        tickMarkSpace = Math.max(tickMarkSpace,
                this.minorTickMarkOutsideLength);
    }
    space.add(tickMarkSpace, edge);
    return space;
}