当前位置: 首页>>代码示例>>Java>>正文


Java FontMetrics.stringWidth方法代码示例

本文整理汇总了Java中java.awt.FontMetrics.stringWidth方法的典型用法代码示例。如果您正苦于以下问题:Java FontMetrics.stringWidth方法的具体用法?Java FontMetrics.stringWidth怎么用?Java FontMetrics.stringWidth使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.awt.FontMetrics的用法示例。


在下文中一共展示了FontMetrics.stringWidth方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import java.awt.FontMetrics; //导入方法依赖的package包/类
public static void main(String[] args) {
	FontMetrics fontMetrics=new JLabel().getFontMetrics(new Font("宋体",Font.PLAIN,12));
	String text="我是中国人,我来自China,好吧!top和bottom文档描述地很模糊,其实这里我们可以借鉴一下TextView对文本的绘制,"
			+ "TextView在绘制文本的时候总会在文本的最外层留出一些内边距,为什么要这样做?因为TextView在绘制文本的时候考虑到了类似读音符号,"
			+ "下图中的A上面的符号就是一个拉丁文的类似读音符号的东西";
	int columnWidth=50;
	long start=System.currentTimeMillis();
	int totalLineHeight=0;
	int singleLineHeight=fontMetrics.getHeight();
	StringBuffer multipleLine=new StringBuffer();
	StringBuffer sb=new StringBuffer();
	for(int i=0;i<text.length();i++){
		char str=text.charAt(i);
		sb.append(str);
		int width=fontMetrics.stringWidth(sb.toString());
		if(width>columnWidth){
			sb.deleteCharAt(sb.length()-1);
			if(multipleLine.length()>0){
				multipleLine.append("\r");
				totalLineHeight+=singleLineHeight;
			}
			multipleLine.append(sb);
			sb.delete(0, sb.length());
			sb.append(str);
		}
	}
	if(multipleLine.length()>0){
		multipleLine.append("\r");
	}
	if(sb.length()>0){			
		multipleLine.append(sb);
	}
	long end=System.currentTimeMillis();
	System.out.println(end-start);
	System.out.println(multipleLine.toString());
	System.out.println("totalLineHeight:"+totalLineHeight);
}
 
开发者ID:youseries,项目名称:ureport,代码行数:38,代码来源:Cell.java

示例2: getMinimumSize

import java.awt.FontMetrics; //导入方法依赖的package包/类
@Override
public Dimension getMinimumSize() {
    Dimension minSize = new Dimension();

    if (superIsButton) {
        minSize = super.getMinimumSize();
    } else {

        Graphics g = getGraphics();
        FontMetrics metrics = g.getFontMetrics();

        minSize.width = metrics.stringWidth(labelString) + 14;
        minSize.height = metrics.getMaxAscent()
                + metrics.getMaxDescent() + 9;

        g.dispose();
        g = null;
    }
    return minSize;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:LightweightEventTest.java

示例3: getPreferredSize

import java.awt.FontMetrics; //导入方法依赖的package包/类
public Dimension getPreferredSize() {
    int w = 0;
    int h = 0;
    Graphics g = PropUtils.getScratchGraphics(this);
    FontMetrics fm = g.getFontMetrics(getFont());

    if (getIcon() != null) {
        w = getIcon().getIconWidth();
        h = getIcon().getIconHeight();
    }

    if (getBorder() != null) {
        Insets ins = getBorder().getBorderInsets(this);
        w += (ins.left + ins.right);
        h += (ins.bottom + ins.top);
    }

    w += (fm.stringWidth(getText()) + 22);
    h = Math.max(fm.getHeight(), h) + 2;

    return new Dimension(w, h);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:RadioInplaceEditor.java

示例4: createLegendItem

import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
 * Creates a legend item
 *
 * @param graphics  the graphics device.
 * @param item  the legend item.
 * @param x  the x coordinate.
 * @param y  the y coordinate.
 *
 * @return the legend item.
 */
private DrawableLegendItem createLegendItem(Graphics graphics,
                                            LegendItem item, double x, double y) {

    int innerGap = 2;
    FontMetrics fm = graphics.getFontMetrics();
    LineMetrics lm = fm.getLineMetrics(item.getLabel(), graphics);
    float textHeight = lm.getHeight();

    DrawableLegendItem drawable = new DrawableLegendItem(item);

    float xloc = (float) (x + innerGap + 1.15f * textHeight);
    float yloc = (float) (y + innerGap + (textHeight - lm.getLeading() - lm.getDescent()));

    drawable.setLabelPosition(new Point2D.Float(xloc, yloc));

    float boxDim = textHeight * 0.70f;
    xloc = (float) (x + innerGap + 0.15f * textHeight);
    yloc = (float) (y + innerGap + 0.15f * textHeight);

    drawable.setMarker(new Rectangle2D.Float(xloc, yloc, boxDim, boxDim));

    float width = (float) (drawable.getLabelPosition().getX() - x
                           + fm.stringWidth(item.getLabel()) + 0.5 * textHeight);

    float height = 2 * innerGap + textHeight;
    drawable.setBounds(x, y, width, height);
    return drawable;

}
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:40,代码来源:MeterLegend.java

示例5: centerText

import java.awt.FontMetrics; //导入方法依赖的package包/类
public static int centerText(Direction direction, Graphics graphics, java.awt.Rectangle bounds, String text) {
	FontMetrics metrics = graphics.getFontMetrics();
	switch(direction) {
	case HORRIZONTAL: return bounds.x+bounds.width/2-metrics.stringWidth(text)/2;
	case VERTICAL: return bounds.y+(int)((bounds.height-metrics.getStringBounds(text, graphics).getHeight())/2+metrics.getAscent());
	default: return 0; }
}
 
开发者ID:kristian,项目名称:JDigitalSimulator,代码行数:8,代码来源:Guitilities.java

示例6: getFittingString

import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
 * Get string that will be shorter than maxWidth. If Passed text is too long
 * return part of text with "..." at the end.
 * @param text Text we want to fit into maxWidth
 * @param metrics font metrics to measure length of strings
 * @param maxWidth maximal length the returned string can fit into.
 * @return text if it fits into maxWidth, otherwise maximal text.substring(0,X).concat("...")
 *              that will fit into maxWidth.
 */
private String getFittingString(String text, FontMetrics metrics, int maxWidth) {
    if (metrics.stringWidth(text) < maxWidth) {
        return text;
    }

    for (int index = text.length() - 1; index > 0; index--) {
        String shorter = text.substring(0, index).concat("...");
        if (metrics.stringWidth(shorter) < maxWidth) {
            return shorter;
        }
    }
    return "...";
}
 
开发者ID:kefik,项目名称:Pogamut3,代码行数:23,代码来源:PoshWidget.java

示例7: drawString

import java.awt.FontMetrics; //导入方法依赖的package包/类
public void drawString(Graphics g, int x, int y, Font f, String s) {
    g.setFont(f);
    FontMetrics metrics = g.getFontMetrics();
    int width = metrics.stringWidth( s );
    int height = metrics.getHeight();
    g.drawString( s, x*cellSizeW+(cellSizeW/2-width/2), y*cellSizeH+(cellSizeH/2+height/2));
}
 
开发者ID:nickrfer,项目名称:code-sentinel,代码行数:8,代码来源:GridWorldView.java

示例8: paintTransparentFrame

import java.awt.FontMetrics; //导入方法依赖的package包/类
protected void paintTransparentFrame() {
    Dimension size = component.getComponent().getSize();
    if (component.getComponent() instanceof JComponent) {
        JComponent jc = (JComponent) component.getComponent();
        jc.paintImmediately(0, 0, size.width, size.height);
    }
    if (disposed) {
        return;
    }
    size = component.getSize();
    Point location = component.getLocation();
    graphics.setColor(BG);
    graphics.fillRect(0 + location.x, 0 + location.y, size.width, size.height);
    String name = component.getRComponentName();
    graphics.setColor(Color.WHITE);
    Font font = new Font(graphics.getFont().getName(), Font.ITALIC | Font.BOLD, 12);
    FontMetrics metrics = graphics.getFontMetrics(font);
    int stringWidth = metrics.stringWidth(name);
    int stringHeight = metrics.getHeight() / 2;
    if (stringWidth < size.width && stringHeight < size.height) {
        graphics.setFont(font);
        graphics.drawString(name, (size.width - stringWidth) / 2 + location.x, (size.height + stringHeight) / 2 + location.y);
    } else if (stringWidth >= size.width || stringHeight >= size.height) {
        graphics.setFont(new Font(graphics.getFont().getName(), Font.ITALIC, 9));
        graphics.drawString(name, 0 + location.x, (size.height + stringHeight) / 2 + location.y);
    } else {
        logger.warning("Not drawing");
    }
}
 
开发者ID:jalian-systems,项目名称:marathonv5,代码行数:30,代码来源:TransparentFrame.java

示例9: paint

import java.awt.FontMetrics; //导入方法依赖的package包/类
@Override
public void paint(Graphics g) {
    int w = getSize().width;
    int h = getSize().height;
    if (img == null) {
        super.paint(g);
        g.setColor(Color.black);
        FontMetrics fm = g.getFontMetrics();
        int x = (w - fm.stringWidth(calcString)) / 2;
        int y = h / 2;
        g.drawString(calcString, x, y);
    } else {
        g.drawImage(img, 0, 0, w, h, this);
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:16,代码来源:DitherTest.java

示例10: computeFitText

import java.awt.FontMetrics; //导入方法依赖的package包/类
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;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:35,代码来源:DashboardUtils.java

示例11: textRight

import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
 * Write the given text string in the current font, right-aligned at (<em>x</em>, <em>y</em>).
 *
 * @param  x the <em>x</em>-coordinate of the text
 * @param  y the <em>y</em>-coordinate of the text
 * @param  text the text to write
 */
public static void textRight(double x, double y, String text) {
    if (text == null) throw new IllegalArgumentException();
    offscreen.setFont(font);
    FontMetrics metrics = offscreen.getFontMetrics();
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = metrics.stringWidth(text);
    int hs = metrics.getDescent();
    offscreen.drawString(text, (float) (xs - ws), (float) (ys + hs));
    draw();
}
 
开发者ID:DCMMC,项目名称:Java-Algorithms-Learning,代码行数:19,代码来源:StdDraw.java

示例12: runTest

import java.awt.FontMetrics; //导入方法依赖的package包/类
public void runTest(Object ctx, int numReps) {
    SWContext swctx = (SWContext)ctx;
    String text = swctx.text;
    FontMetrics fm = swctx.fm;
    int wid = 0;
    do {
        wid += fm.stringWidth(text);
    } while (--numReps >= 0);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:TextMeasureTests.java

示例13: paintString

import java.awt.FontMetrics; //导入方法依赖的package包/类
private void paintString(Graphics g, String msg) {
	Font old = g.getFont();
	g.setFont(old.deriveFont(Font.BOLD).deriveFont(18.0f));
	FontMetrics fm = g.getFontMetrics();
	int x = (getWidth() - fm.stringWidth(msg)) / 2;
	if (x < 0)
		x = 0;
	g.drawString(msg, x, getHeight() - 23);
	g.setFont(old);
	return;
}
 
开发者ID:LogisimIt,项目名称:Logisim,代码行数:12,代码来源:Canvas.java

示例14: calculateBaseUnits

import java.awt.FontMetrics; //导入方法依赖的package包/类
private void calculateBaseUnits() {
    // This calculation comes from:
    // http://support.microsoft.com/default.aspx?scid=kb;EN-US;125681
    FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics(
                                     UIManager.getFont("Button.font"));
    baseUnitX = metrics.stringWidth(
                  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    baseUnitX = (baseUnitX / 26 + 1) / 2;
    // The -1 comes from experimentation.
    baseUnitY = metrics.getAscent() + metrics.getDescent() - 1;
}
 
开发者ID:fesch,项目名称:Moenagade,代码行数:12,代码来源:WindowsLayoutStyle.java

示例15: splitText

import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
 * Split some text at word boundaries into a list of strings that
 * take up no more than a given width.
 *
 * @param text The text to split.
 * @param delim Characters to consider as word delimiting.
 * @param fontMetrics {@code FontMetrics} used to calculate
 *     text width.
 * @param width The text width maximum.
 * @return A list of split text.
 */
public static List<String> splitText(String text, String delim,
                                     FontMetrics fontMetrics, int width) {
    List<String> result = new ArrayList<>();
    final int len = text.length();
    int i = 0, start;
    String top = "";
    Character d = null;
    for (;;) {
        for (; i < len; i++) {
            if (delim.indexOf(text.charAt(i)) < 0) break;
        }
        if (i >= len) break;
        start = i;
        for (; i < len; i++) {
            if (delim.indexOf(text.charAt(i)) >= 0) break;
        }
        String s = text.substring(start, i);
        String t = (top.isEmpty()) ? s : top + d + s;
        if (fontMetrics.stringWidth(t) > width) {
            if (top.isEmpty()) {
                result.add(s);
            } else {
                result.add(top);
                top = s;
            }
        } else {
            top = t;
        }
        if (i >= len) {
            if (!top.isEmpty()) result.add(top);
            break;
        }
        d = text.charAt(i);
    }
    return result;
}
 
开发者ID:FreeCol,项目名称:freecol,代码行数:48,代码来源:StringUtils.java


注:本文中的java.awt.FontMetrics.stringWidth方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。