Text in Java Applets

I’m writing a Java Applet with a fixed size, say 500 x 500. I’m using the paint function and the drawString command. I have a string so long that it goes off the right edge of the applet. Is there any command that will make Java format such a string intelligently?

I don’t think that there’s a simple command, but it shouldn’t be hard to figure out your own word wrap routine in Java. (Maybe not easy, though…)
You’d need to:

Figure out how much space you have to work with between the point you start drawing, and the ‘margin’.

Get the graphical font metrics from the paint function

use the stringWidth routine to see if the graphical length of the string would exceed what is required, and if so, chop off words (or build them up) and start at the longest possible prefix that will fit on one line.

Drop down vertically by the fontmetrics height and start over again with what is left of the string you need to print.
Hmm… maybe I’ll write my own word-wrapping applet just as an exercise now. :slight_smile:

This code sample seems to get okay results, but you may need to fiddle with the right looping value (270 in this case) because my applet with was 320, and even allowing for the margins on each side I can’t seem to account for some of that gap.

msgText is an applet-level variable containing what to print.

	public void paint (Graphics g) {
		int linevert = 10;
		int h, i, j, w;
		FontMetrics fm = g.getFontMetrics();
		h = fm.getHeight();
		String tempString = msgText;
		String tPrint;
		tPrint = "";
		while (! tempString.equals ("")) {
			linevert += h;
			i = 1;
			w = 0;
			j = 0;
			while (w <= 270 && j < tempString.length()) {
				j = tempString.indexOf (" ", i);
				if (j == -1) j = tempString.length() + 1;
				tPrint = tempString.substring (0, j);
				w = fm.stringWidth (tPrint);
				i = j + 1;
			if (w > 270) tPrint = tempString.substring (0, i - 1);
			g.drawString (tPrint, 10, linevert);
			tempString = tempString.substring (tPrint.length() + 1);