javax.swing.JComponent#getFontMetrics ( )源码实例Demo

下面列出了javax.swing.JComponent#getFontMetrics ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: FlatLaf   文件: FlatToolTipUI.java
@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 );
}
 
源代码2 项目: FlatLaf   文件: FlatToolTipUI.java
@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 );
}
 
源代码3 项目: openjdk-jdk9   文件: bug8132119.java
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!");
        }
    }
 
源代码4 项目: openjdk-jdk9   文件: bug8132119.java
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) + "...");
    }
 
源代码5 项目: openjdk-jdk9   文件: bug8132119.java
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");
}
 
源代码6 项目: openjdk-jdk9   文件: bug8132119.java
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");
}
 
源代码7 项目: seaglass   文件: SeaGlassToolTipUI.java
/**
 * @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;
}
 
源代码8 项目: tn5250j   文件: SessionBean.java
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);
}
 
源代码9 项目: magarena   文件: TextComponent.java
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));

}
 
源代码10 项目: netbeans   文件: AbstractViewTabDisplayerUI.java
protected final FontMetrics getTxtFontMetrics() {
    if (fm == null) {
        JComponent control = getDisplayer();
        fm = control.getFontMetrics(getTxtFont());
    }
    return fm;
}
 
源代码11 项目: netbeans   文件: QuickSearchPopup.java
/** 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;
}
 
源代码12 项目: netbeans   文件: DashboardUtils.java
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;
}
 
源代码13 项目: netbeans   文件: QuickSearchPopup.java
/** 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;
}
 
源代码14 项目: openjdk-jdk9   文件: bug8132119.java
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);
}
 
源代码15 项目: knopflerfish.org   文件: JLabelled.java
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);
}
 
源代码16 项目: PolyGlot   文件: PToolTipUI.java
@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;
}
 
源代码17 项目: pdfxtk   文件: MultiLineToolTip.java
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);
   }
 
源代码18 项目: netbeans   文件: UIUtils.java
public static int getColumnWidthInPixels(String str, JComponent comp) {
    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    return fm.stringWidth(str);
}
 
源代码19 项目: Bytecoder   文件: SwingUtilities2.java
/**
 * 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);
}