Applet Example Draw Strings and Graphics

Applet Example Draw Strings and Graphics


Applet Example: Printing System Date

Let us practice one more applet that prints the system date.

1st File: Applet – DateDemo.java

2nd File: HTML – DD.html


Applet Example
Screenshot of DD.html

The same execution procedure of previous applet is to be followed.

Date d = new Date();

The above statement creates Date object. Date is from java.util package.

String s1 = d.toString();

The drawString() method requires a string as first parameter. So, convert Date object d into a string using toString() method of Object class (or alternatively, valueOf() method of String class can also be used).

g.drawString(s1, 50, 80 );

The string s1 is painted at x-coordinate of 50 and y-coordinate of 80 pixels.

Applet Example: Drawing Graphics

Java permits to draw graphics with applets. The Graphics includes many methods to draw lines, rectangles and ovals, polygons etc. About these methods we discuss later clearly in AWT – Graphics topic.

File Name: DrawingGraphics.java

File Name: DrawingGraphics.html

Applet Example
Screenshot of Applet Example DrawingGraphics.html

Let us see the methods of Graphics class used in the above program.

drawRect(60, 70, 110, 70) Draws a rectangle at x and y coordinates of 60 and 70 with a width and height of 110 and 70 pixels
drawOval(180, 70, 135, 70) Draws a oval at x and y coordinates of 180 and 70 with a width and height of 135 and 70
drawArc(50, 150, 120, 100, 0, 180) Draws an arc at x and y coordinates of 50 and 150, arc width of 120 and arc height of 100 and start angle with 0 and ending angle with 180
drawLine(180, 150, 240, 240) Takes four integer parameters of line coordinates of x1, y1 and x2, y2

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 *