Use of the Canvas Class
As with most things, there's more than one way to accomplish most tasks in
Java. Here's a way of using an instance of the Canvas class to draw stuff in
an applet:
---------------------------------------------------------
import java.awt.*;
import java.applet.*;
public class diagonal1 extends Applet{
public void init(){
setBackground(Color.white);
setLayout(new BorderLayout());
add("Center", new D1());
}
}
class D1 extends Canvas{
public void paint(Graphics g){
Dimension d = getSize();
int maxX = d.width -1, maxY = d.height -1;
g.setColor(Color.red);
g.drawLine(0,maxY,maxX,0);
}
}
//
---------------------------------------------------------
That's pretty simple and easy to understand, especially in the light of the
last lesson. Here's a more interesting example:
import java.awt.*;
import java.applet.*;
public class can2 extends Applet{
public void init(){
setBackground(Color.white);
C1 a = new C1();
C2 b = new C2();
C1 c = new C1();
C2 d = new C2();
a.setSize(50,50);
b.setSize(50,50);
c.setSize(20,20);
d.setSize(30,30);
add(a);
add(b);
add(c);
add(d);
}
}
class C1 extends Canvas{
public void paint(Graphics g){
Dimension d = getSize();
g.setColor(Color.red);
g.fillRect(0,0,d.width,d.height);
}
}
class C2 extends Canvas{
public void paint(Graphics g){
Dimension d = getSize();
g.setColor(Color.red);
g.fillOval(0,0,d.width,d.height);
}
}
//
---------------------------------------------------------
Assignment:
Create an applet which contains four peace signs displayed in four different
sizes. Each peace sign must be drawn in a class which extends Canvas. You
will create four instances of this class and you will simply make each a
different size. Your peace sign should be displayed using atleast three
different colors.