6

Does anyone know of existing code that lets you draw fully justified text in Java2D?

For example, if I said, drawString("sample text here", x, y, width), is there an existing library that could figure out how much of that text fits within the width, do some inter-character spacing to make the text look good, and automatically do basic word wrapping?

2 Answers 2

20

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.

1
  • Thanks - I actually started working on a similar method, and there are a number of similarities in our approach. I'm also adding some logic that can tweak the inter-character spacing. Dec 30, 2008 at 16:27
1

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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.