2012-11-11 74 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