Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding the length of text

Status
Not open for further replies.

kosmokramer

Programmer
Sep 8, 2002
73
US
Hey. This is probably an easy question, but how do you find the length of text in terms of how many pixels it will take up on the applet? I am making a java slideshow, and I have the text description next to the image. The problem is that sometimes the text runs off the side of the applet. I tried reading the javadoc to find something and came up with LineBreakMeasurer, but the example they provide seems unnecessarily complicated (that, and I didn't really understand all the terminology used!). All I want to do is find the length of the string in pixels so that I can wrap to the next line!!

Thanks,
Paul
 
java.awt.Font font = new Font("Serif", Font.PLAIN, 12);
java.awt.FontMetrics fontMetrics = getFontMetrics(font);

int width = fontMetrics.stringWidth("HATTUSAS");
int height = fontMetrics.getHeight();


hope this helps.[pipe]

Salih Sipahi
Software Engineer.
City of Istanbul Turkey
s.sipahi@sahinlerholding.com.tr
turkey_clr.gif
 
Thanks for your help, however I have one more question. I have it working, but sometimes it shows only parts of the string, not the whole thing. Here is the code (I know it is not the most efficient code, but it gets the job done!)

Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.FontMetrics.*;

public class rotatePictures extends Applet implements ActionListener
{
    private Button back,forward;
    private String [] imageArray;
	private String [] descriptionArray;
	private String currentDescription;
    private int index = 0;
    private Image image;
    private int iCount = 1; 
   
    public void init()
    {
        setLayout(new BorderLayout());
		
		Panel bottom = new Panel();
		back = new Button("Back");
		forward = new Button("Forward");
        
		bottom.add(back);
		bottom.add(forward);
        add("South", bottom);
		
		back.addActionListener(this);
        forward.addActionListener(this);
		
        iCount = Integer.parseInt(getParameter("imageCount"));
        imageArray = new String[iCount];
		descriptionArray = new String[iCount];
		
        for (int i=1; i<=iCount; i++)
        {
			imageArray[i-1] = getParameter((&quot;loadPictures&quot;+i));
			descriptionArray[i-1] = getParameter((&quot;description&quot;+i));
        }
		
		image = getImage(getDocumentBase(),imageArray[index]);
		currentDescription = descriptionArray[index];
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == back)
        {
            if (index!=0)
            {
                index--;
				image = getImage(getDocumentBase(),imageArray[index]);
				currentDescription = descriptionArray[index];
				System.out.println(index);
            }
            else
            {
                index = (imageArray.length-1);
                image = getImage(getDocumentBase(), imageArray[index]);
				currentDescription = descriptionArray[index];
				System.out.println(index);
            }
        }
        else if (e.getSource() == forward)
        {
            if (index<(imageArray.length-1))
            {
                index++;
				image = getImage(getDocumentBase(),imageArray[index]);
				currentDescription = descriptionArray[index];
				System.out.println(index);
            }
            else
            {
                index = 0;
                image = getImage(getDocumentBase(),imageArray[index]);
				currentDescription = descriptionArray[index];
				System.out.println(index);
            }
        }
        repaint();
    }
	
    public void paint(Graphics g)
    {
		int appletW = Integer.parseInt(getParameter(&quot;appletWidth&quot;));
		int appletH = Integer.parseInt(getParameter(&quot;appletHeight&quot;));
		Graphics2D g2;
        g2 = (Graphics2D) g;
		setBackground(Color.white);
		FontRenderContext frc = g2.getFontRenderContext();
		Font f = new Font(&quot;Comic Sans MS&quot;, Font.BOLD, 16);
		String theTitle = getParameter(&quot;title&quot;);
		TextLayout t1 = new TextLayout(theTitle, f, frc);
		g2.setColor(Color.red);
		FontMetrics fMeasure = getFontMetrics(f);
		int fontWidth = fMeasure.stringWidth(theTitle);
		int titleStartW = (appletW-fontWidth)/2;
		t1.draw(g2, titleStartW, 40);
		int width = image.getWidth(this);
		int height = image.getHeight(this);
		if (width>=appletW || (height+50)>=appletH)
		{
			g.drawString(&quot;The image is too big to be drawn&quot;, 20, appletH/2);
			g.drawString(&quot;in the space provided by the applet!!&quot;, 20, appletH/2+15);
		}
		else
		{
			int centerWidth = (appletW-width)/2;
			int centerHeight = (appletH-50-height)/2; 
			g.drawImage(image, centerWidth, centerHeight, this);
			Font f2 = new Font(&quot;Comic Sans MS&quot;, Font.PLAIN, 10);
			TextLayout t2 = new TextLayout(currentDescription, f2, frc);
			FontMetrics fMeasure2 = getFontMetrics(f2);
			int descriptionWidth = fMeasure2.stringWidth(currentDescription);
			int descriptionHeight = fMeasure2.getHeight();
			int descriptionStartW = (appletW - width)/2 + width + 10;
			int descriptionStartH = appletH/2;
			if(descriptionWidth+descriptionStartW>appletW)
			{
				int newHeightIndex = 0;
				while(fMeasure2.stringWidth(currentDescription)+descriptionStartW>appletW)
				{
					String theCurrentString = currentDescription.substring(0,1);
					currentDescription = currentDescription.substring(1,currentDescription.length());
					int tempWidth = fMeasure2.stringWidth(theCurrentString);
					while(tempWidth+descriptionStartW<appletW)
					{
						theCurrentString += currentDescription.substring(0,1);
						currentDescription = currentDescription.substring(1,currentDescription.length());
						tempWidth = fMeasure2.stringWidth(theCurrentString);
					}
					TextLayout t3 = new TextLayout(theCurrentString, f2, frc);
					t3.draw(g2, descriptionStartW, descriptionStartH+(newHeightIndex*15));
					newHeightIndex++;
				}
				TextLayout t4 = new TextLayout(currentDescription, f2, frc);
				t4.draw(g2, descriptionStartW, descriptionStartH+(newHeightIndex*15));
			}
			else
			{
				t2.draw(g2, descriptionStartW, descriptionStartH);
			}
		}	
    }
};

and here is my sample webpage:

Code:
<html>
<body>
<applet code=&quot;rotatePictures.class&quot; height=&quot;400&quot; width=&quot;400&quot;>
<Param Name=&quot;title&quot; value=&quot;This is a sample photo album&quot;>
<Param Name=&quot;imageCount&quot; value=&quot;4&quot;>
<Param Name=&quot;appletWidth&quot; value=&quot;400&quot;>
<Param Name=&quot;appletHeight&quot; value=&quot;400&quot;>
<Param Name=&quot;loadPictures1&quot; value=&quot;1.jpg&quot;>
<Param Name=&quot;description1&quot; value=&quot;Something goes here.&quot;>
<Param Name=&quot;loadPictures2&quot; value=&quot;2.jpg&quot;>
<Param Name=&quot;description2&quot; value=&quot;This is a really long description that will not fit on one line.&quot;>
<Param Name=&quot;loadPictures3&quot; value=&quot;3.jpg&quot;>
<Param Name=&quot;description3&quot; value=&quot;Yet another description.&quot;>
<Param Name=&quot;loadPictures4&quot; value=&quot;4.jpg&quot;>
<Param Name=&quot;description4&quot; value=&quot;Last description&quot;>
</applet>
</body>
</html>

P.S. the pictures I use are all about 150 pixels wide and 220 tall
 
Well I must admit I had some time with that problem but I think I solved it.
Before this you should be aware of that when you are using graphical user interface (java,other GUIs) the application must protect its view.For example when a window opens and stays in front of your application,the GUI window when the other window minimizes must reload its view.Java applets do this by calling its paint method again.
This is where your problem begins.When you call the long line you are destroying your currentDescription variable.
&quot;currentDescription = currentDescription.substring(1,currentDescription.length());&quot; and finally your variable
becomes &quot; one line&quot; as a value.So when the paint method is recalled,the long sentences goes away.
To prevent this store the initial value into another variable.After typing the graphic onto the screen, modidy the currentDescription into the initial state.
This is what I mean :

public void paint(Graphics g)
{
int appletW = Integer.parseInt(getParameter(&quot;appletWidth&quot;));
int appletH = Integer.parseInt(getParameter(&quot;appletHeight&quot;));
String initial=new String(currentDescription);
...
...
....
Your methods part
...
TextLayout t4 = new TextLayout(currentDescription, f2, frc);
t4.draw(g2, descriptionStartW, descriptionStartH+(newHeightIndex*15));
currentDescription=new String(initial);
}
else
{
t2.draw(g2, descriptionStartW, descriptionStartH);

}

}
}

Salih Sipahi
Software Engineer.
City of Istanbul Turkey
s.sipahi@sahinlerholding.com.tr
turkey_clr.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top