Java Code Examples for java.awt.FontMetrics.stringWidth()

The following are Jave code examples for showing how to use stringWidth() of the java.awt.FontMetrics class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ureport   File: Cell.java   View Source Code Vote up 6 votes
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);
}
 
Example 2
Project: openjdk-jdk10   File: LightweightEventTest.java   View Source Code Vote up 6 votes
@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;
}
 
Example 3
Project: incubator-netbeans   File: RadioInplaceEditor.java   View Source Code Vote up 6 votes
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);
}
 
Example 4
Project: parabuild-ci   File: MeterLegend.java   View Source Code Vote up 5 votes
/**
 * 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;

}
 
Example 5
Project: JDigitalSimulator   File: Guitilities.java   View Source Code Vote up 5 votes
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; }
}
 
Example 6
Project: Pogamut3   File: PoshWidget.java   View Source Code Vote up 5 votes
/**
 * 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 "...";
}
 
Example 7
Project: code-sentinel   File: GridWorldView.java   View Source Code Vote up 5 votes
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));
}
 
Example 8
Project: marathonv5   File: TransparentFrame.java   View Source Code Vote up 5 votes
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");
    }
}
 
Example 9
Project: OpenJSharp   File: DitherTest.java   View Source Code Vote up 5 votes
@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);
    }
}
 
Example 10
Project: incubator-netbeans   File: DashboardUtils.java   View Source Code Vote up 5 votes
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 11
Project: Java-Algorithms-Learning   File: StdDraw.java   View Source Code Vote up 5 votes
/**
 * 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();
}
 
Example 12
Project: openjdk-jdk10   File: TextMeasureTests.java   View Source Code Vote up 5 votes
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);
}
 
Example 13
Project: Logisim   File: Canvas.java   View Source Code Vote up 5 votes
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;
}
 
Example 14
Project: Moenagade   File: WindowsLayoutStyle.java   View Source Code Vote up 5 votes
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;
}
 
Example 15
Project: freecol   File: StringUtils.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 16
Project: java-course   File: BarChartComponent.java   View Source Code Vote up 5 votes
/**
 * Calculates max number width for y-axis numeration.
 * 
 * @param g
 *            The {@link Graphics} object.
 * @return Maximum number width.
 */
private int getNumberWidthY(Graphics g) {
    FontMetrics fm = g.getFontMetrics();

    int dimension = 0;
    int yValueStart = chart.getyMin();
    int yValueEnd = chart.getyMax();
    int yValue = Math.max(Math.abs(yValueEnd), Math.abs(yValueStart));

    int width = fm.stringWidth(Integer.toString(yValue));
    dimension = Math.max(width, dimension);

    return dimension;
}
 
Example 17
Project: myster   File: MCListHeader.java   View Source Code Vote up 5 votes
public String makeFit(String s, int size) {

        FontMetrics tempfont = callback.getFontMetrics(callback.getFont()); //uses
        // default
        // font

        int i = 0;
        if (tempfont.stringWidth(s) > size - 8) {
            for (i = s.length(); ((tempfont.stringWidth(s.substring(0, i) + "...") > size - 8) && i > 0); i--)
                ;
            return s.substring(0, i) + "...";
        }
        return s;
    }
 
Example 18
Project: brModelo   File: baseDrawer.java   View Source Code Vote up 4 votes
public void bordaTopDown(Graphics2D g, boolean isTop) {
        FontMetrics fm = g.getFontMetrics();
        String vl = FormateUnidadeMedida(W);
        int xini = getLeft() + margem;
        int pre_y = (isTop ? getTop() : getTopHeight());
        int xfim = getLeftWidth() - margem;
        int yfim = pre_y + (isTop ? 2 : -2);

        int traco = largTraco < margem ? largTraco : margem;
        traco = (isTop ? traco : -traco);
        int ytraco = yfim;
//        int xini = getLeft() + margem;
//        int pre_y = (isTop ? getTop() : getTopHeight() - margem);
//        int xfim = getLeftWidth() - margem;
//        int yfim = pre_y + margem / 2;
//
//        int traco = largTraco < margem ? largTraco : margem;
//        int ytraco = pre_y + (margem - traco) / 2;

        g.setColor(getCorRegua());
        g.drawLine(xini, ytraco, xini, ytraco + 2 * traco);
        g.drawLine(xfim, ytraco, xfim, ytraco + 2 * traco);
        g.drawLine(xini, yfim, xfim, yfim);

        int blc = calculeSubEspaco(W);
        int sr = xini;
        int dv = modInteiro(blc);
        int subblc = 0;
        if (dv > 0) {
            subblc = blc / dv;
        }
        while (sr < xfim) {
            if (dv > 0) {
                int a = subblc;
                while (a < blc) {
                    if (sr + a < xfim) {
                        g.drawLine(sr + a, ytraco, sr + a, ytraco + traco / 2);
                    }
                    a += subblc;
                }
            }
            sr += blc;
            if (sr < xfim) {
                g.drawLine(sr, ytraco, sr, ytraco + traco);
            }
        }

        if (isMostrarTextoRegua()) {
            g.setColor(getForeColor());
            yfim = pre_y + (isTop ? margem / 2 : -margem / 2);
            xini = xini + (W - fm.stringWidth(vl)) / 2;
            int yini = yfim + (fm.getHeight()) / 2 - fm.getDescent();
            g.drawString(vl, xini, yini);
        }
    }
 
Example 19
Project: gitplex-mit   File: AvatarGenerator.java   View Source Code Vote up 4 votes
private static void drawCenteredString(String s, int w, int h, Graphics g) {
	FontMetrics fm = g.getFontMetrics();
	int x = (w - fm.stringWidth(s)) / 2;
	int y = h / 2 - (fm.getAscent() + fm.getDescent()) / 2 + fm.getAscent() + 5;
	g.drawString(s, x, y);
}
 
Example 20
Project: java-course   File: BarChartComponent.java   View Source Code Vote up 2 votes
/**
 * Calculates text width.
 * 
 * @param text
 *            Input text.
 * @param g
 *            The {@link Graphics} object.
 * @return Text width.
 */
private int getTextWidth(String text, Graphics g) {
    FontMetrics fm = g.getFontMetrics();
    return fm.stringWidth(text);
}