R4R
Right Place For Right Person TM
 

R4R JAVAAWT ExamplesDraw Multicolor Text lines

previous

Home

Next

Draw Multicolor Text lines

In this example we are going to set color of different lines.
To set the color of object we have to use method setColor();.
In this we are using Graphics class and Applet class
void setColor(Color newcolor ); This method is used to set color of object or string.
paint(Graphics g);
This method is used to paint the applet.
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. Then we have create a class and extends this class with Applet Class to accurse the property of applet. We had override paint method of applet class.
In our example we use g.setColor (Color new color) before every next line ("string",g) to set different color for different line . Here new color specifies the new drawing color which is blue for  first Line and red for second line and green for third line .



//display multiple line of text
import java.awt.*;
import java.applet.*;
/*<applet code="MultiColorLine" width=300 hight=200>
</applet>
*/
public class MultiColorLine 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();
g.setColor(Color.blue);
nextLine("this is Blue line. ",g);
g.setColor(Color.red);
nextLine("this is Red line",g);
g.setColor(Color.green);
nextLine("this is Green 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);
}
}

Download Source Code

Output Of Example

previous

Home

Next

New Updates

R4R
R4R
R4R
R4R
R4R
R4R
R4R
R4R