Question

In the code, I am reading an xml file and painting the contents accordingly on a JPanel. If the file contains a tag <LineBreak/> I am supposed to insert a Line Break before the next word. I thought I could use a

g.drawString(..)

but that requires that I know what follows the break, which in this case, I do not. Is there any other way to do this by overriding the draw method?

Really appreciate the help. Thanks

Was it helpful?

Solution

I think you will need to use FontMetrics (g.getFontMetrics()) to determine the number of vertical pixels needed to display a line of text. When you call drawString to paint the second line of text, you must pass a y value large enough that the second line of text is drawn below the first line of text.

String[] lines = myStringFromXmlDoc.split("\r\n|\r|\n");
int verticalOffset = 0; // your starting offset would probably be more dynamic
foreach(String line : lines)
{
    g.drawString(line, 0, verticalOffset);
    // use FontMetrics to implement calcLineHeight for yourself
    int currentLineHeight = calcLineHeight(line, g);
    verticalOffset += currentLineHeight;
}

Edit:

Also see java.awt.font.LineBreakMeasurer for a possibly useful utility class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top