Java Programing laungage

adplus-dvertising
Multiple Lines in java
Previous Home Next

In this example we are write multiple lines in java using font metrics. In this we are using Graphics class and Applet class.

void nextLine(String s, Graphics g): This method is used to write text in same line.

void sameLine(String s, graphics g): This method is used to write text in different line.

g.drawString (s ,curX, curY): It is use for draw string.

Font metrics use for mainly two purpose first is to determine the spacing between line of text and the second is to determine the length of the string.

Here first we are importing two packages. Then after we have write applet tag into comments. In this tag we have pass three arguments code ,height and width. The code attribute is used to call the applet class. And Height , width is used for Sizing the window.

Here we have two coordinate at the starting of programming int curX and curY at the starting point both value is zero. At each time when a new line is desired , the Y coordinate must be advance to the beginning of the next line. At each time a string is displayed , the coordinate must be set to the point at which the string ends. to determine the length of the string in pixels of previous string we have to call stringwidth().We use this value to advance the X coordinate each time you display a line. To increment the value of Y coordinate we have to call get Height()

Example

//display multiple line of text using FontMetrics
import java.awt.*;
import java.applet.*;
/*<applet code="MultiLine" width=200 height=200>
</applet>
*/
public class MultiLine extends Applet{
int curX=0, curY=0;
public void init(){
Font f=new Font("SanfAerif",Font.ITALIC,20);
setFont (f);
}
public void paint(Graphics g){
FontMetrics fm=g.getFontMetrics();
nextLine("this is first line. ",g);
sameLine("this is same line",g);
nextLine("this is second line",g);
nextLine("this is third line",g);
}
void nextLine(String s,Graphics g){
FontMetrics fm=g.getFontMetrics();
curY+=fm.getHeight();                      
curX=0;
g.drawString(s,curX,curY);
curX=fm.stringWidth(s);

}void sameLine(String s,Graphics g){
FontMetrics fm=g.getFontMetrics();
g.drawString(s,curX,curY);
curX+=fm.stringWidth(s);
}
}

Output of Example:

Download Source Code

Previous Home Next