Concurrent Programming with Java
Lab Manual, Version 1.0, F. Astha Ekadiyanto, 2002.

[Contents] [Next] [Previous]

Lab 3: Building Applets - Graphical representation


Adding draw(Graphics) method in Rbs Class

By now, your x-Cell SubClasses should have arrows pointed to the Visualization Interface.
You may notice the difference of this kind of arrow compared with others. The arrow indicates that the SubClasses implements the Interface.

In Java, a SubClass can only inherits from one SuperClass, but can implement more that one Interface.
Correspondingly, an Interface (or extends) can inherits from more than one SuperInterface, since it only define method signatures.

Implementing the draw(Graphics) method in Rbs Class actually do not require Visualization Interface. This because Rbs is an individual class that have no other SuperClass rather than the Object Class itself. Therefore, implementing the Interface will not give any purpose rather than just a signature.

Open Editor on the Rbs Class and we will define the draw(Graphics) method. Inside the method, we first call the draw(Graphics) method of the cellAssigned in the Rbs. We cannot call the draw(Graphics) method from the Cell Class (since it is not defined in the Cell Class). And since by declaration in the Rbs, we do not know whether the Cell is a SquareCell or CircleCell or HexCell, we cannot cast them immediately to the subClasses. Fortunately, we have defined that all the Cell SubClasses implements a common Visualization interface that define the draw(Graphics) method. Thus, we can cast the cellAssigned into a Visualization implementing Object before calling the draw(Graphics) method.

 ((Visualization)cellAssigned).draw(g);

Then we would like to represent the Rbs existance by drawing a small circle point at the center of the Cell.

int x = (int) (cellAssigned.getX());
int y = (int) (cellAssigned.getY()); g.fillOval(x-1,y-1,3,3);

The complete implementation in Java is shown below.

import java.util.*;
import java.awt.Graphics;
import java.awt.Color; public class Rbs implements Enumeration {
     // . . . all other code of the original Rbs Class
       
     public void draw(Graphics g)
     {
Color normalColor = g.getColor();
((Visualization)cellAssigned).draw(g);
int x = (int) (cellAssigned.getX());
int y = (int) (cellAssigned.getY());
g.setColor(new Color(122,0,255));
g.fillOval(x-1,y-1,3,3);
g.setColor(normalColor); } }

 


[Contents] [Next] [Previous]