2012-11-11 75 views
0

这是我在我的第一本书中的最后一个练习,但是当我运行应用程序的形状没有被绘制时,我很难过,因为没有错误。形状,可绘制的“形状名”,形状的继承和接口

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

Rectangle类

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

让我们从开始,Java是大小写敏感的,所以public void Paint (Graphics g){永远不会是CAL由Java引导,方法名称为paint

然后让我们继续前进,如果有的话,您应该很少扩展顶级容器,如JFrame,尤其是覆盖paint方法。 paint做了很多非常重要的工作,你应该总是调用super.paint

相反,你应该从什么JPanel延伸并覆盖paintComponent方法,而不是(记住调用super.paintComponwnt

然后我会包括罗希特的建议。

你可能想通过

+0

我可以踢自己有一个读,非常感谢。 – Melky