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?
-
Although not the most elegant nor robust solution, here's an method that will take the
Font
of the currentGraphics
object and obtain itsFontMetrics
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 ofString
by using thesplit
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 thecurX
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.David : 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. -
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...
-
Hi
how to paint multiple icons (ie., say icons between text) in jlabel using graphics? plz do assist me in this effort
Thanks
0 comments:
Post a Comment