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…
Final Code
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);
If I understand correctly, your issues is with the rectangle’s height.
Try keeping a record of how many lines you have eg:
This also changes how it works out the y value for drawing the string.
Would something like that work?