Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full-justification with a Java Graphics.drawString replacement?

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?

like image 520
David Koelle Avatar asked Dec 30 '08 15:12

David Koelle


2 Answers

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.

like image 194
coobird Avatar answered Nov 16 '22 12:11

coobird


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

like image 1
PhiLho Avatar answered Nov 16 '22 12:11

PhiLho