Applet Example: Drawing Strings and Graphics in Applets given with Screenshots in Simple terms for a Beginner.
After practicing the earlier simple life cycle program, let us write another program that prints some strings on applet window (not at DOS prompt as done previously). Now we use the java.awt.Graphics object passed as parameter to paint() method.
The application includes two files – Demo.java, applet file and Demo.html, HTML file. HTML file should be opened in a browser using File menu .
Applet Example: 1st File: Applet – Demo.java
public class Demo extends Applet
String s1, s2;
public void init()
s1 = "Welcome to way2java practices";
s2 = "on today " + new java.util.Date();
public void paint(Graphics g)
g.drawString(s1, 50, 50);
g.drawString(s2, 50, 70);
g.drawString("Best Wishes", 50, 90); // directly writing a string
public void destroy()
s1 = null;
s2 = null;
2nd File: HTML – Demo.html
<applet code="Demo.class" width="250" height="250">
Compile the Demo.java file as usual at DOS prompt as in the previous program. Let us run this program both using appletviewer and browser.
Execution using appletviewer: C:\snr\way2java\applets> appletviewer Demo.html
Execution using browser: Open the Demo.html file through File menu of browser.
Two strings are assigned with some values in init() method and used in paint() method. Graphics is an abstract class and includes many methods of drawing. Here we use drawString() method. The drawString() takes three parameters – the first one is a string that is to be drawn, the second and third parameters are integer values of x and y coordinates in pixels, the position of the string on the applet window. Remember, the left top corner of the window is 0, 0 pixels. The other methods of drawing, we come to know in AWT Graphics
Note: All the methods of Applet class are concrete methods (not abstract). The programmer can override what ever methods he would like and the other that are not used, are implicitly created and called by the browser (like the default constructor in an application).