形状,可绘制的“Shapename”,形状继承和接口

时间:2012-11-11 18:33:22

标签: java interface abstract implements

这是我在第一本书中的最后一次练习,但是当我运行应用程序时,形状没有被绘制,我很难过,因为没有错误。

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();
}

1 个答案:

答案 0 :(得分:1)

让我们先说一下,Java区分大小写,因此Java永远不会调用public void Paint (Graphics g){,因为方法名称为paint

然后让我们继续前进,你应该很少(如果有的话)扩展像JFrame这样的顶级容器,尤其是覆盖paint方法。 paint执行了许多非常重要的工作,您应该始终致电super.paint

相反,您应该从某个JPanel延伸并覆盖paintComponent方法(记住要调用super.paintComponwnt

然后我会包括Rohit的建议。

您可能希望阅读