I want to draw string using Graphics with Rectangle border outside the string.
This is what I already do:
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);
}
My problem is, I want to draw string with new line ("\n") with Rectangle border outside:
This is the code for the new line:
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());
}
}
Can anyone help me for this problem? I appreciate your help & suggestion...
No comments:
Post a Comment