當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。