Reputation: 3456
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);
Upvotes: 1
Views: 2635
Reputation: 12883
You could also create a regular JLabel object, and then set its text with html and include a
tag. e.g. myLabel.setText("<html>aString<br>Test</html>");
, then add a border with a single line to the JLabel.
Upvotes: 0
Reputation: 2494
If I understand correctly, your issues is with the rectangle's height.
Try keeping a record of how many lines you have eg:
int numberOfLines=0;
for (String line : str.split("\n")) {
g2d.drawString(line, x , y + (numberOfLines * height));
numberOfLines++;
}
g2d.drawRect(x - 2, y - height + 2, width + 4, height * numberOfLines);
This also changes how it works out the y value for drawing the string.
Would something like that work?
Upvotes: 3