Today in Java, i will teach you how to create java program that will have the drawString method in creating graphics in applet.
The
drawString() method, takes as parameters an instance of the String class containing the text to be drawn, and two integer values specifying the coordinates where the text is placed (x and y coordinates in the screen).
So, now let's start this tutorial!
1. Open JCreator or NetBeans and make a java program with a file name of
drawString.java. In the classname, extend a java.applet.Applet to have an applet library.
2. Import java.awt.* package because we will have the Graphics and Font class library.
3. Create a
paint() function to paint and draw the graphics in the applet. Then have this code inside the paint() function.
// initialize a name variable to be displayed in the drawString method
// set the font style to Times New Roman with a plain text and a font size of 30
g.
setFont(new Font("TimesRoman",
Font.
PLAIN,
30));
//font color is set to Red
//and then draw the string with the specific coodrinates
g.drawString(name, 50, 100);
}
The drawString() method calls your variable name and it has the x and y coordinates.
drawString(String text, int x, int y)
Note: You have to build your program to have the .class file extension for viewing of the applet.
4. Now, create a new file. Click File Type, choose Other Folder and click HTML Applet.
After creating it, it will have the given code. Then in the Applet Code, put and encode your file name of the created java file, the drawString.class. Follow this code below:
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body bgcolor="000000">
<center>
<applet
code = "drawString.class"
width = "500"
height = "300"
>
</applet>
</center>
</body>
</html>
Press F5 to run the program.
Output:
Full source code of the drawString.java:
import java.awt.*;
public class drawString
extends java.
applet.
Applet {
// initialize a name variable to be displayed in the drawString method
// set the font style to Times New Roman with a plain text and a font size of 30
g.
setFont(new Font("TimesRoman",
Font.
PLAIN,
30));
//font color is set to Red
//and then draw the string with the specific coodrinates
g.drawString(name, 50, 100);
}
}
Best Regards,
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Mobile: 09488225971
Landline: 826-9296
E-mail:
[email protected]
Add and Follow me on Facebook:
https://www.facebook.com/donzzsky
Visit and like my page on Facebook at:
https://www.facebook.com/BermzISware