我想在字符串外使用带有矩形边框的图形来绘制字符串。
这是我已经做的:
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
FontMetrics fontMetrics = g2d.getFontMetrics();
String str = "aString Test";
int width = fontMetrics.stringWidth(str);
int height = fontMetrics.getHeight();
int x = 100;
int y = 100;
// Draw String
g2d.drawString(str, x, y);
// Draw Rectangle Border based on the string length & width
g2d.drawRect(x - 2, y - height + 2, width + 4, height);
}
我的问题是,我想用新行(“\ n”)绘制字符串,外面有矩形边框:
这是新行的代码:
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
FontMetrics fontMetrics = g2d.getFontMetrics();
String str = "aString\nTest";
int width = fontMetrics.stringWidth(str);
int height = fontMetrics.getHeight();
int x = 100;
int y = 100;
// Drawing string per line
for (String line : str.split("\n")) {
g2d.drawString(line, x, y += g.getFontMetrics().getHeight());
}
}
谁能帮我解决这个问题?感谢您的帮助和建议...
最终代码
int numberOfLines = 0;
for (String line : str.split("\n")) {
if(numberOfLines == 0)
g2d.drawString(line, x, y);
else
g2d.drawString(line, x, y += g.getFontMetrics().getHeight());
numberOfLines++;
}
g2d.drawRect(x - 2, y - height * numberOfLines + 2, width + 4, height * numberOfLines);