下面列出了javax.swing.plaf.basic.BasicGraphicsUtils#getStringWidth ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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!");
}
}
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) + "...");
}
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");
}
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);
}
public static int stringWidth(JComponent c, FontMetrics fm, String string) {
return (int) BasicGraphicsUtils.getStringWidth(c, fm, string);
}