Example usage for java.awt FontMetrics stringWidth

List of usage examples for java.awt FontMetrics stringWidth

Introduction

In this page you can find the example usage for java.awt FontMetrics stringWidth.

Prototype

public int stringWidth(String str) 

Source Link

Document

Returns the total advance width for showing the specified String in this Font .

Usage

From source file:Main.java

/**
 * "Fixates" the preferred width of the given label to the given text.
 * //from   www.  j a  v a 2s.  com
 * @param aLabel
 *          the label to fixate, cannot be <code>null</code>;
 * @param aMinimalText
 *          the text to use as minimal width indicator.
 */
public static final void fixLabelWidth(final JLabel aLabel, final String aMinimalText) {
    final FontMetrics fm = aLabel.getFontMetrics(aLabel.getFont());
    final int height = fm.getHeight();

    aLabel.setPreferredSize(new Dimension(fm.stringWidth(aMinimalText), height));
}

From source file:GraphicsUtil.java

static public Rectangle getTextBounds(Graphics g, String text, int x, int y, int halign, int valign) {
    if (g == null)
        return new Rectangle(x, y, 0, 0);
    FontMetrics mets = g.getFontMetrics();
    int width = mets.stringWidth(text);
    int ascent = mets.getAscent();
    int height = ascent + mets.getDescent();
    Rectangle ret = new Rectangle(x, y, width, height);

    switch (halign) {
    case H_CENTER:
        ret.translate(-(width / 2), 0);/*  ww  w .  j  av a2s  .c om*/
        break;
    case H_RIGHT:
        ret.translate(-width, 0);
        break;
    default:
        ;
    }
    switch (valign) {
    case V_TOP:
        break;
    case V_CENTER:
        ret.translate(0, -(ascent / 2));
        break;
    case V_BASELINE:
        ret.translate(0, -ascent);
        break;
    case V_BOTTOM:
        ret.translate(0, -height);
        break;
    default:
        ;
    }
    return ret;
}

From source file:org.drugis.addis.gui.wizard.TreatmentCategorizationOverviewWizardStep.java

public static VisualizationViewer<DecisionTreeNode, DecisionTreeEdge> buildDecisionTreeView(
        final DecisionTree tree) {
    // Crazy hack because sizes start at 600x600 by default.
    final Layout<DecisionTreeNode, DecisionTreeEdge> layout = new TreeLayout<DecisionTreeNode, DecisionTreeEdge>(
            new DecisionTree(new LeafNode()), 150, 75);
    layout.getSize().height = 1;//www.  j a  v  a2  s. co m
    layout.getSize().width = 1;
    layout.setGraph(tree);

    final VisualizationViewer<DecisionTreeNode, DecisionTreeEdge> vv = new VisualizationViewer<DecisionTreeNode, DecisionTreeEdge>(
            layout);

    vv.setVertexToolTipTransformer(new ToStringLabeller<DecisionTreeNode>());
    vv.getRenderContext().setVertexFillPaintTransformer(new Transformer<DecisionTreeNode, Paint>() {
        public Paint transform(final DecisionTreeNode node) {
            return (node instanceof LeafNode) ? new Color(0.55f, 0.55f, 1.0f) : Color.ORANGE;
        }
    });

    vv.getRenderContext().setVertexShapeTransformer(new Transformer<DecisionTreeNode, Shape>() {
        public Shape transform(final DecisionTreeNode input) {
            final FontMetrics fontMetrics = vv.getGraphics().getFontMetrics();
            final double width = fontMetrics.stringWidth(input.toString()) + 6;
            final double height = fontMetrics.getHeight() + 2;
            final double arc = 5;
            return new RoundRectangle2D.Double(-width / 2, -height / 2, width, height, arc, arc);
        }
    });

    vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<DecisionTreeNode>());

    vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<DecisionTreeEdge>());
    vv.getRenderContext().getEdgeLabelRenderer().setRotateEdgeLabels(false);
    vv.getRenderContext().setEdgeLabelClosenessTransformer(
            new ConstantDirectionalEdgeValueTransformer<DecisionTreeNode, DecisionTreeEdge>(0.5, 0.4));
    return vv;
}

From source file:org.bitbucket.mlopatkin.android.logviewer.widgets.UiHelper.java

public static boolean isTextFit(JComponent component, int width, String text) {
    FontMetrics m = component.getFontMetrics(component.getFont());
    int textWidth = m.stringWidth(text);
    return textWidth <= width;

}

From source file:Main.java

/**
 * Returns the size of the given text computed towards to the given
 * component./*from   w  ww .ja  v  a  2  s .  c o  m*/
 *
 * @param c the component where the text is contained
 * @param text the text to measure
 * @return the dimensions of the text
 */
public static Dimension getStringSize(Component c, String text) {
    // get metrics from the graphics
    FontMetrics metrics = c.getFontMetrics(c.getFont());
    // get the height of a line of text in this font and render context
    int hgt = metrics.getHeight();
    // get the advance of my text in this font and render context
    int adv = metrics.stringWidth(text);
    // calculate the size of a box to hold the text with some padding.
    return new Dimension(adv + 2, hgt + 2);
}

From source file:org.swiftexplorer.gui.AboutDlg.java

public static void show(Component parent, HasLocalizedStrings stringsBundle) {
    URI uri = null;/*w  w  w  .  ja v a  2 s.c o m*/
    try {
        uri = new URI("http://www.swiftexplorer.org");
    } catch (URISyntaxException e) {
        logger.error("URL seems to be ill-formed", e);
    }
    final String buttontext = "www.swiftexplorer.org";

    Box mainBox = Box.createVerticalBox();
    mainBox.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));

    StringBuilder sb = loadResource("/about.html");
    JLabel label = new JLabel(sb.toString());
    label.getAccessibleContext().setAccessibleDescription(getTitle(stringsBundle));
    mainBox.add(label);

    if (uri != null) {
        JButton button = new JButton();
        button.setText(buttontext);
        button.setToolTipText(uri.toString());
        button.addActionListener(new OpenUrlAction(uri));
        FontMetrics metrics = button.getFontMetrics(button.getFont());
        if (metrics != null)
            button.setSize(metrics.stringWidth(buttontext), button.getHeight());
        button.getAccessibleContext().setAccessibleDescription(buttontext);
        mainBox.add(button);
    }

    mainBox.add(Box.createVerticalStrut(10));

    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    panel.add(mainBox);

    JOptionPane.showMessageDialog(parent, panel, getTitle(stringsBundle), JOptionPane.INFORMATION_MESSAGE,
            getIcon());
}

From source file:StringUtils.java

/**
 * Given a line of text and font metrics information, wrap the line and add
 * the new line(s) to <var>list</var>.
 * // w  w  w. j a  v a  2 s  .c om
 * @param line
 *          a line of text
 * @param list
 *          an output list of strings
 * @param fm
 *          font metrics
 * @param maxWidth
 *          maximum width of the line(s)
 */
public static void wrapLineInto(String line, List list, FontMetrics fm, int maxWidth) {
    int len = line.length();
    int width;
    while (len > 0 && (width = fm.stringWidth(line)) > maxWidth) {
        // Guess where to split the line. Look for the next space before
        // or after the guess.
        int guess = len * maxWidth / width;
        String before = line.substring(0, guess).trim();

        width = fm.stringWidth(before);
        int pos;
        if (width > maxWidth) // Too long
            pos = findBreakBefore(line, guess);
        else { // Too short or possibly just right
            pos = findBreakAfter(line, guess);
            if (pos != -1) { // Make sure this doesn't make us too long
                before = line.substring(0, pos).trim();
                if (fm.stringWidth(before) > maxWidth)
                    pos = findBreakBefore(line, guess);
            }
        }
        if (pos == -1)
            pos = guess; // Split in the middle of the word

        list.add(line.substring(0, pos).trim());
        line = line.substring(pos).trim();
        len = line.length();
    }
    if (len > 0)
        list.add(line);
}

From source file:net.roboconf.doc.generator.internal.GraphUtils.java

/**
 * Computes the width of a shape for a given component or facet.
 * @param type a type//from  www  . j  av a 2s.co  m
 * @return the width it should take once displayed as a graph vertex
 */
public static int computeShapeWidth(AbstractType type) {

    Font font = GraphUtils.getDefaultFont();
    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    FontMetrics fm = img.getGraphics().getFontMetrics(font);

    int width = fm.stringWidth(type.getName());
    width = Math.max(width, 80) + 20;
    return width;
}

From source file:Main.java

public static Dimension getTextDimension(final String text, final Font font) {
    if (defaultLabel == null) {
        defaultLabel = new JLabel();
    }//from w w  w.  ja va 2 s  .  c om

    // get metrics from the graphics
    FontMetrics fontMetrics = defaultLabel.getFontMetrics(font);

    // get the height of a line of text in this
    // font and render context
    int hgt = fontMetrics.getHeight();
    // get the advance of my text in this font
    // and render context
    int adv = fontMetrics.stringWidth(text);
    // calculate the size of a box to hold the text
    Dimension size = new Dimension(adv, hgt);

    return size;
}

From source file:juicebox.tools.utils.juicer.apa.APAPlotter.java

/**
 * Plot text centered at a point (rather than from the upper left corner as is the default)
 *
 * @param g2       graphics2D object// w ww. j av  a 2 s .  c o m
 * @param text     to be plotted
 * @param position of where text will be centered at
 */
private static void drawCenteredString(Graphics2D g2, String text, Point position) {
    FontMetrics fm = g2.getFontMetrics();
    int x2 = position.x - fm.stringWidth(text) / 2;
    int y2 = fm.getAscent() + (position.y - (fm.getAscent() + fm.getDescent()) / 2);
    g2.drawString(text, x2, y2);
}