Applet Example Draw Strings and Graphics

Applet Example Draw Strings and Graphics


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

2nd File: HTML – Demo.html


Applet Example
Screenshot when run with appletviewer – Demo.html

Applet Example
Screenshot when run with browser – Demo.html

Execution

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).

3 thoughts on “Applet Example Draw Strings and Graphics

  1. moaz amin

    sir Graphics is an Abstract class then how we create object of Graphics to call methods drawString() it is very confuseable for me

  2. sangeeth reddy

    sir executing the above code gives following error.. 1) “paint (java.awt.Graphics) in Awt cannot override paint(java.awt.Graphics) in java.awt.Container; overriding method is static
    public static void paint(Graphics g)
    ^
    2) non-static variable s1 cannot be referenced from a static context g.drawString(s1, 100, 100);
    ^

    2) non-static variable s1 cannot be referenced from a static context g.drawString(s2, 100, 100);
    ^

Leave a Reply

Your email address will not be published. Required fields are marked *