This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello ! I'm trying to draw a string that contains several words on a Canvas (50*100 pix) . The problem is that I would like to draw a new line so the sentence can fit inside the canvas. The string differs from time to time and varies in length. How can I solve this problemo, I would like to be able to check the length of the string in pixels an then make a new line when the String reaches over the width of the canvas. I Hope u understand my problem and that u have some good solution ! I use the method drawString in the Graphics class Thanx Chris
Wow, well the number of pixels that a string takes up is very dependant on the font that you are using (big letters take more, some fonts have different widths for different letters etc.) You could try experimenting with the font that you are using, and trying to estimate how many characters can fit in 100 pixels, and just going with that. Other than that I don't really have a good idea.
"JavaRanch, where the deer and the Certified play" - David O'Meara
you need to use java.awt.FontMetrics to obtain the width of the string, and then decide where to break it apart based on the width of your applet. i think the code for width is: [/B] i think the code to break it up will be pretty easy (kind of like Java-1b in the Cattle Drive) so let me know if you want me to give it a shot. [This message has been edited by Greg Harris (edited April 23, 2001).]
Joined: Apr 23, 2001
Hi Greg Thanx for your help. I read something�s about a subclass to java.awt.Font called LineBreakMeasure, I wonder if I can use it to solve my problem ? I will try your solution and if you have the time I would appreciate to se you�re code to split up the sentence so the wrapping of words are correctly done. Thanx again Chris
Joined: Apr 12, 2001
here is what i have so far... this justs tests if the string is too long, and prints an alternative message if it does. the LineBreakMeasure sounds like it might be useful...
i know this is messy, but at least you can see how FontMetrics works. i will try to break up the string in a little while.
Joined: Apr 12, 2001
i think i found what you need... i have to run to class now, but i will try to figure it out later. i need to do the same thing for an applet, so this will help me as well. sun.java.com
you can use the class java.util.StringTokenizer to split your message String into individual words. And then use the FontMetrics to determine the pixel-length of strings, and StringBuffer to construct each line of your sentence. here is an example...