0

这是我在 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();
}
4

1 回答 1

1

让我们开始吧,Java 是区分大小写的,所以public void Paint (Graphics g){永远不会被 Java 调用,因为方法名是paint

然后让我们继续,你应该很少,如果有的话,扩展一个顶级容器JFrame,特别是覆盖该paint方法。paint做了很多非常重要的工作,你应该总是打电话super.paint

相反,您应该从某些东西扩展JPanel并覆盖该paintComponent方法(记住调用super.paintComponwnt

然后我会包括 Rohit 的建议。

您可能想通读

于 2012-11-11T19:47:55.893 回答