这是我在 headfirst 书中的最后一个练习,但是当我运行应用程序时,没有绘制形状,我很困惑,因为没有错误。
public class ShapesDriver extends Frame{ //You said Frame in the Tutorial4 Document
private ArrayList<Drawable> drawable;
public static void main(String args[]){
ShapesDriver gui = new ShapesDriver();
gui.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
}
public ShapesDriver(){
super("Shapes");
setSize(500, 500);
setResizable(false);
setVisible(true);
show();
}
public void Paint (Graphics g){
DrawableRectangle rect1 = new DrawableRectangle(150, 100);
drawable.add(rect1);
for(int i = 0; i < drawable.size(); i++){
drawable.get(i).draw(g);
}
}
}
DrawableRectangle 类
public class DrawableRectangle extends Rectangle implements Drawable{
private int x, y;
public DrawableRectangle(int height, int width){
super(height, width);
}
@Override
public void setColour(Color c) {
this.setColour(c);
}
@Override
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void draw(Graphics g) {
g.drawRect(x, y, width, height);
}
}
矩形类
public abstract class Rectangle implements Shape {
public int height, width;
Rectangle(int Height, int Width){
this.height = Height;
this.width = Width;
}
@Override
public double area() { return width * height; }
}
形状类
public interface Shape {
public double area();
}