A fairly standard demonstration of object-oriented programming is storing graphic objects of various types in a container and scrolling through the container drawing the objects. You might think that a hierarchy of graphics classes would be part of every object-oriented language. The opposite is true. Most windowing systems have a graphics class that handles draw routines for the windows, and this class contains functions to draw various graphic objects. In Java the class Graphics (in the package java.AWT) is used to draw on an object such as a panel. In this note you will learn to creata a hierarchy and store it in an ArrayList container.
The hierarchy of graphic objects must have a standard set of functions specified someplace. Some early systems used point as a base class to define the methods for all graphic classes. It is actually better to define an abstract base class to create the standard interface. Create a new class file by selecting "new" from the file menu and "class" from the new tab. Then enter the following code for the abstract base class in the file.
package Graphic;
import java.awt.Graphics;
public interface MyGraphic {
public void draw(Graphics g);
}
The rectangle class is a fairly common class to implement. To avoid naming problems it is called MyRect.
package Graphic;
import java.awt.*;
public class MyRect implements MyGraphic{
int xFirst,xLast,yFirst,yLast;
Color color;
public MyRect(int x1,int y1, int x2, int y2,Color c){
xFirst = x1;
yFirst = y1;
xLast = x2;
yLast = y2;
color = c;
}
public void draw(Graphics g) {
g.setColor(color);
g.drawRect(xFirst,yFirst,xLast,yLast);
}
}
Storing graphic objects in an array can cause problems since the ArrayList container stores Objects. All classes are descendents of Object, so there is no problem inserting items in an ArrayList, but when you retrieve an item you must return it to the hierarchy it was created in. This is done by typecasting. You will notice in the paint function below that when an item is retrieved from the array, it is typecast as MyGraphic. This allows us to use any of the methods from the base class.
// End of Frame Class
class DrawPanel extends JPanel{
ArrayList item = new ArrayList();
Color color= Color.black;
public DrawPanel(){}
public void setPanelColor(Color c){
color = c;
}
public void addItem(MyGraphic one){
item.add(one);
}
public void clear(){
item.clear();
}
public void paint(Graphics g)
{
super .paintComponents(g);
g.setColor(color);
for (int i=0;i < item.size();i++){
MyGraphic local = (MyGraphic)item.get(i);
local.draw(g);
}
}
}