Applet Example: Printing System Date
Let us practice one more applet that prints the system date.
1st File: Applet – DateDemo.java
import java.awt.*;
import java.applet.*;
import java.util.*;
public class DateInfo extends Applet
{
public void paint(Graphics g)
{
Date d = new Date();
String s1 = d.toString();
g.drawString(s1, 50, 80 );
}
}
2nd File: HTML – 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
import java.awt.*;
import java.applet.*;
public class DrawingGraphics extends Applet
{
public void paint(Graphics g)
{
g.drawRect(60, 70, 110, 70);
g.drawOval(180, 70, 135, 70);
g.drawArc(50, 150, 120, 100, 0, 180);
g.drawLine(180, 150, 240, 240);
g.drawLine(260, 150, 180, 240);
}
}
File Name: DrawingGraphics.html
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 |
sir Graphics is an Abstract class then how we create object of Graphics to call methods drawString() it is very confuseable for me
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);
^
Send me the code.