Full-justification with a Java Graphics.drawString replacement?

Solution 1:

Although not the most elegant nor robust solution, here's an method that will take the Font of the current Graphics object and obtain its FontMetrics in order to find out where to draw the text, and if necessary, move to a new line:

public void drawString(Graphics g, String s, int x, int y, int width)
{
    // FontMetrics gives us information about the width,
    // height, etc. of the current Graphics object's Font.
    FontMetrics fm = g.getFontMetrics();

    int lineHeight = fm.getHeight();

    int curX = x;
    int curY = y;

    String[] words = s.split(" ");

    for (String word : words)
    {
        // Find out thw width of the word.
        int wordWidth = fm.stringWidth(word + " ");

        // If text exceeds the width, then move to next line.
        if (curX + wordWidth >= x + width)
        {
            curY += lineHeight;
            curX = x;
        }

        g.drawString(word, curX, curY);

        // Move over to the right for next word.
        curX += wordWidth;
    }
}

This implementation will separate the given String into an array of String by using the split method with a space character as the only word separator, so it's probably not very robust. It also assumes that the word is followed by a space character and acts accordingly when moving the curX position.

I wouldn't recommend using this implementation if I were you, but probably the functions that are needed in order to make another implementation would still use the methods provided by the FontMetrics class.

Solution 2:

For word wrapping, you might be interested by How to output a String on multiple lines using Graphics. No justification here, not sure if it is easy (or impossible!) to add...