Example usage for javax.swing JComponent getGraphics

List of usage examples for javax.swing JComponent getGraphics

Introduction

In this page you can find the example usage for javax.swing JComponent getGraphics.

Prototype

@BeanProperty(bound = false)
public Graphics getGraphics() 

Source Link

Document

Returns this component's graphics context, which lets you draw on a component.

Usage

From source file:Main.java

/**
 * Returns a string abbreviated according to the length of the available space
 * in a component./*from  w  ww .  ja v  a2s . com*/
 * @param str A string which may need abbreviating.
 * @param component The component the string will be rendered in.
 * @return a string abbreviated according to the length of the available space
 */
public static String abbreviate(String str, JComponent component) {
    String result = "";
    if (component != null) {
        Graphics g = component.getGraphics();
        FontMetrics fm = g.getFontMetrics(component.getFont());
        int stringSize = SwingUtilities.computeStringWidth(fm, str);
        final int border = 48;
        int availableWidth = component.getWidth() - border;
        if (stringSize > availableWidth) {
            final int avCharWidth = fm.charWidth('x');
            final int alwaysChop = 5;
            final int charsToChop = alwaysChop + ((stringSize - availableWidth) / avCharWidth);
            final int leftPos = (str.length() - charsToChop) / 2;
            final int maxLength = str.length() - charsToChop;
            final int left = leftPos > 0 ? leftPos : 0;
            final int len = maxLength > left ? maxLength : left + 1;
            result = abbreviate(str, left, len);
        } else {
            result = str;
        }
    }
    return result;
}

From source file:Main.java

public static Rectangle calculateBoundsForComponent(JComponent comp, String text, int xOffset, int yOffset) {

    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    Rectangle2D bounds = fm.getStringBounds(text, comp.getGraphics());

    return new Rectangle(xOffset + (int) bounds.getX(), yOffset,
            (int) Math.ceil(bounds.getWidth()) + (PADDING * 2),
            (int) Math.ceil(bounds.getHeight() + fm.getDescent()) + (PADDING * 2));
}