Java Code Examples for javax.swing.JComponent#getFontMetrics()

The following examples show how to use javax.swing.JComponent#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: FlatToolTipUI.java    From FlatLaf with Apache License 2.0 6 votes vote down vote up
@Override
public void paint( Graphics g, JComponent c ) {
	if( isMultiLine( c ) ) {
		FontMetrics fm = c.getFontMetrics( c.getFont() );
		Insets insets = c.getInsets();

		FlatUIUtils.setRenderingHints( (Graphics2D) g );
		g.setColor( c.getForeground() );

		List<String> lines = StringUtils.split( ((JToolTip)c).getTipText(), '\n' );

		int x = insets.left + 3;
		int x2 = c.getWidth() - insets.right - 3;
		int y = insets.top - fm.getDescent();
		int lineHeight = fm.getHeight();
		JComponent comp = ((JToolTip)c).getComponent();
		boolean leftToRight = (comp != null ? comp : c).getComponentOrientation().isLeftToRight();
		for( String line : lines ) {
			y += lineHeight;
			FlatUIUtils.drawString( c, g, line, leftToRight ? x : x2 - SwingUtilities.computeStringWidth( fm, line ), y );
		}
	} else
		super.paint( HiDPIUtils.createGraphicsTextYCorrection( (Graphics2D) g ), c );
}
 
Example 2
Source File: TextComponent.java    From magarena with GNU General Public License v3.0 6 votes vote down vote up
TextComponent(
    final String text,
    final JComponent component,
    final Font aFont,
    final boolean isChoice,
    final String aCardInfo,
    final Color choiceColor,
    final Color interactiveColor) {

    this.text = text;
    this.cardInfo = aCardInfo;

    this.fontColor = getTextColor(isChoice, choiceColor, interactiveColor);
    this.font = getTextFont(aFont);
    this.metrics = component.getFontMetrics(this.font);

    this.newLine = !(".".equals(text) || ",".equals(text));

}
 
Example 3
Source File: SessionBean.java    From tn5250j with GNU General Public License v2.0 6 votes vote down vote up
private static Dimension deriveOptimalSize(JComponent comp, Font f
                                           , Border brdr, int nrChars
                                           , int nrLines)
{
  if (comp == null)
    return null;

  FontMetrics fm = null;
  Graphics g = comp.getGraphics();

  if (g != null)
    fm = g.getFontMetrics(f);
  else
    fm = comp.getFontMetrics(f);

  Insets insets = (brdr == null) ? new Insets(0, 0, 0, 0)
                                 : brdr.getBorderInsets(comp);
  int height = (fm.getHeight() * nrLines) + insets.top+ insets.bottom;
  int width = (nrChars * fm.charWidth('M')) + insets.left + insets.right;

  return new Dimension(width + 2, height);
}
 
Example 4
Source File: SeaGlassToolTipUI.java    From seaglass with Apache License 2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public Dimension getPreferredSize(JComponent c) {
    SeaGlassContext context = getContext(c);
    Insets insets = c.getInsets();
    Dimension prefSize = new Dimension(insets.left + insets.right, insets.top + insets.bottom);
    String text = ((JToolTip) c).getTipText();

    if (text != null) {
        View v = (c != null) ? (View) c.getClientProperty("html") : null;
        if (v != null) {
            prefSize.width += (int) v.getPreferredSpan(View.X_AXIS);
            prefSize.height += (int) v.getPreferredSpan(View.Y_AXIS);
        } else {
            Font font = context.getStyle().getFont(context);
            FontMetrics fm = c.getFontMetrics(font);
            prefSize.width += context.getStyle().getGraphicsUtils(context).computeStringWidth(context, font, fm, text);
            prefSize.height += fm.getHeight();
        }
    }
    context.dispose();
    return prefSize;
}
 
Example 5
Source File: bug8132119.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void checkNullArgumentsGetStringWidth(JComponent comp,
        String text) {

    FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont());
    BasicGraphicsUtils.getStringWidth(null, fontMetrics, text);
    float result = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, null);

    if (result != 0) {
        throw new RuntimeException("The string length is not 0");
    }

    try {
        BasicGraphicsUtils.getStringWidth(comp, null, text);
    } catch (NullPointerException e) {
        return;
    }

    throw new RuntimeException("NPE is not thrown");
}
 
Example 6
Source File: bug8132119.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void checkNullArgumentsGetClippedString(
        JComponent comp, String text) {

    FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont());

    BasicGraphicsUtils.getClippedString(null, fontMetrics, text, 1);
    String result = BasicGraphicsUtils.getClippedString(comp, fontMetrics, null, 1);
    if (!"".equals(result)) {
        throw new RuntimeException("Empty string is not returned!");
    }

    try {
        BasicGraphicsUtils.getClippedString(comp, null, text, 1);
    } catch (NullPointerException e) {
        return;
    }

    throw new RuntimeException("NPE is not thrown");
}
 
Example 7
Source File: bug8132119.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void testStringClip() {

        String str = "1234567890";
        JComponent comp = createComponent(str);
        FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont());

        int width = (int) BasicGraphicsUtils.getStringWidth(comp, fontMetrics, str);

        String clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, width);
        checkClippedString(str, clip, str);

        clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, width + 1);
        checkClippedString(str, clip, str);

        clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, -1);
        checkClippedString(str, clip, "...");

        clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, 0);
        checkClippedString(str, clip, "...");

        clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics,
                str, width - width / str.length());
        int endIndex = str.length() - 3;
        checkClippedString(str, clip, str.substring(0, endIndex) + "...");
    }
 
Example 8
Source File: bug8132119.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void testStringWidth() {

        String str = "12345678910\u036F";
        JComponent comp = createComponent(str);
        Font font = comp.getFont();
        FontMetrics fontMetrics = comp.getFontMetrics(font);
        float stringWidth = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, str);

        if (stringWidth == fontMetrics.stringWidth(str)) {
            throw new RuntimeException("Numeric shaper is not used!");
        }

        if (stringWidth != getLayoutWidth(str, font, NUMERIC_SHAPER)) {
            throw new RuntimeException("Wrong text width!");
        }
    }
 
Example 9
Source File: FlatToolTipUI.java    From FlatLaf with Apache License 2.0 6 votes vote down vote up
@Override
public Dimension getPreferredSize( JComponent c ) {
	if( isMultiLine( c ) ) {
		FontMetrics fm = c.getFontMetrics( c.getFont() );
		Insets insets = c.getInsets();

		List<String> lines = StringUtils.split( ((JToolTip)c).getTipText(), '\n' );
		int width = 0;
		int height = fm.getHeight() * Math.max( lines.size(), 1 );
		for( String line : lines )
			width = Math.max( width, SwingUtilities.computeStringWidth( fm, line ) );

		return new Dimension( insets.left + width + insets.right + 6, insets.top + height + insets.bottom );
	} else
		return super.getPreferredSize( c );
}
 
Example 10
Source File: QuickSearchPopup.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Computes width of string up to maxCharCount, with font of given JComponent
 * and with maximum percentage of owning Window that can be taken */
private static int computeWidth (JComponent comp, int maxCharCount, int percent) {
    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    int charW = fm.charWidth('X');
    int result = charW * maxCharCount;
    // limit width to 50% of containing window
    Window w = SwingUtilities.windowForComponent(comp);
    if (w != null) {
        result = Math.min(result, w.getWidth() * percent / 100);
    }
    return result;
}
 
Example 11
Source File: bug8132119.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void testDrawString(boolean underlined) {
    String str = "AOB";
    JComponent comp = createComponent(str);

    BufferedImage buffImage = createBufferedImage(WIDTH, HEIGHT);
    Graphics2D g2 = buffImage.createGraphics();

    g2.setColor(DRAW_COLOR);
    g2.setFont(comp.getFont());

    FontMetrics fontMetrices = comp.getFontMetrics(comp.getFont());
    float width = BasicGraphicsUtils.getStringWidth(comp, fontMetrices, str);
    float x = (WIDTH - width) / 2;
    int y = 3 * HEIGHT / 4;

    if (underlined) {
        BasicGraphicsUtils.drawStringUnderlineCharAt(comp, g2, str, 1, x, y);
    } else {
        BasicGraphicsUtils.drawString(comp, g2, str, x, y);
    }
    g2.dispose();

    float xx = BasicGraphicsUtils.getStringWidth(comp, fontMetrices, "A") +
            BasicGraphicsUtils.getStringWidth(comp, fontMetrices, "O")/2;

    checkImageContainsSymbol(buffImage, (int) xx, underlined ? 3 : 2);
}
 
Example 12
Source File: DashboardUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static String computeFitText(JComponent component, int maxWidth, String text, boolean bold) {
    if (text == null) {
        text = ""; // NOI18N
    }
    if (text.length() <= VISIBLE_START_CHARS + 3) {
        return text;
    }
    FontMetrics fm;
    if (bold) {
        fm = component.getFontMetrics(component.getFont().deriveFont(Font.BOLD));
    } else {
        fm = component.getFontMetrics(component.getFont());
    }
    int width = maxWidth;

    String sufix = "..."; // NOI18N
    int sufixLength = fm.stringWidth(sufix + " "); //NOI18N
    int desired = width - sufixLength;
    if (desired <= 0) {
        return text;
    }

    for (int i = 0; i <= text.length() - 1; i++) {
        String prefix = text.substring(0, i);
        int swidth = fm.stringWidth(prefix);
        if (swidth >= desired) {
            if (fm.stringWidth(text.substring(i + 1)) <= fm.stringWidth(sufix)) {
                return text;
            }
            return prefix.length() > 0 ? prefix + sufix : text;
        }
    }
    return text;
}
 
Example 13
Source File: JLabelled.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public JLabelled(String text, String tooltip, JComponent main, int labelWidth)
{
  // This panel is horizontal box.
  setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
  setAlignmentX(Component.LEFT_ALIGNMENT);

  // Shorten text to last part after a dot
  // if it's too long
  final FontMetrics fm = main.getFontMetrics(main.getFont());
  if (fm != null) {
    int ix;
    while (-1 != (ix = text.indexOf("."))
           && fm.stringWidth(text) > labelWidth) {
      text = text.substring(ix + 1);
    }
  }

  final JLabel label = new JLabel(text);
  final Dimension size = label.getPreferredSize();
  label.setPreferredSize(new Dimension(labelWidth, size.height + 2));

  if (tooltip != null && !"".equals(tooltip)) {
    label.setToolTipText("<html>" + tooltip + "</html>");
  }

  // Since we are in a scroll pane with glue at the bottom we do not want the
  // components to stretch vertically.
  main.setMaximumSize(new Dimension(Integer.MAX_VALUE, main
      .getPreferredSize().height));
  label.setMaximumSize(label.getPreferredSize());

  add(label);
  add(main);
}
 
Example 14
Source File: QuickSearchPopup.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Computes width of string up to maxCharCount, with font of given JComponent
 * and with maximum percentage of owning Window that can be taken */
private static int computeWidth (JComponent comp, int maxCharCount, int percent) {
    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    int charW = fm.charWidth('X');
    int result = charW * maxCharCount;
    // limit width to 50% of containing window
    Window w = SwingUtilities.windowForComponent(comp);
    if (w != null) {
        result = Math.min(result, w.getWidth() * percent / 100);
    }
    return result;
}
 
Example 15
Source File: AbstractViewTabDisplayerUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected final FontMetrics getTxtFontMetrics() {
    if (fm == null) {
        JComponent control = getDisplayer();
        fm = control.getFontMetrics(getTxtFont());
    }
    return fm;
}
 
Example 16
Source File: PToolTipUI.java    From PolyGlot with MIT License 5 votes vote down vote up
@Override
public Dimension getPreferredSize(JComponent c) {
    FontMetrics fm = c.getFontMetrics(c.getFont());
    Insets insets = c.getInsets();

    Dimension prefSize = new Dimension(insets.left+insets.right,
                                       insets.top+insets.bottom);
    String text = ((JToolTip)c).getTipText();

    if (text != null && !text.isEmpty()) {
        prefSize.width += fm.stringWidth(text);
        prefSize.height += fm.getHeight();
    }
    return prefSize;
}
 
Example 17
Source File: MultiLineToolTip.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
public Dimension getPreferredSize(JComponent c) {
     FontMetrics metrics = c.getFontMetrics(c.getFont());
     String tipText = ((JToolTip)c).getTipText();
     if(tipText == null) tipText = "";
     
     ArrayList linesa = new ArrayList();
     String[]  strs   = Strings.split(tipText, '\n');
     for(int i = 0; i < strs.length; i++) {     
Segment s = new Segment(strs[i].toCharArray(), 0, strs[i].length());

for(int brk = 0; ;) {
  if(Utilities.getTabbedTextWidth(s, metrics, 0, null, 0) < maxAllowedWidth) {
    linesa.add(new String(s.array, s.offset, s.array.length - s.offset));
    break;
  }
  brk = Utilities.getBreakLocation(s, metrics, 0, maxAllowedWidth, null, 0);
  linesa.add(new String(s.array, s.offset, brk));
  s.offset += brk;
  s.count  -= brk;
}
     }
     
     lines = (String[])linesa.toArray(new String[linesa.size()]);
     maxWidth = 0;
     for(int i = 0; i < lines.length; i++)
maxWidth = Math.max(maxWidth, SwingUtilities.computeStringWidth(metrics, lines[i]));
     return new Dimension(maxWidth + 6, metrics.getHeight() * lines.length + 2);
   }
 
Example 18
Source File: UIUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static int getColumnWidthInPixels(String str, JComponent comp) {
    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    return fm.stringWidth(str);
}
 
Example 19
Source File: SwingUtilities2.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the FontMetrics for the specified Font.
 * This method is used when a Graphics is available, typically when
 * painting.  If a Graphics is not available the JComponent method of
 * the same name should be used.
 * <p>
 * Callers should pass in a non-null JComonent, the exception
 * to this is if a JComponent is not readily available at the time of
 * painting.
 * <p>
 * This does not necessarily return the FontMetrics from the
 * Graphics.
 *
 * @param c JComponent requesting FontMetrics, may be null
 * @param c Graphics Graphics
 * @param font Font to get FontMetrics for
 */
@SuppressWarnings("deprecation")
public static FontMetrics getFontMetrics(JComponent c, Graphics g,
                                         Font font) {
    if (c != null) {
        // Note: We assume that we're using the FontMetrics
        // from the widget to layout out text, otherwise we can get
        // mismatches when printing.
        return c.getFontMetrics(font);
    }
    return Toolkit.getDefaultToolkit().getFontMetrics(font);
}