2016-04-26 51 views
1

Shape類已經當我寫一個抽象的拉伸,這需要Graphics對象...例如,如果我想繪製一個矩形,在殼體2:呼叫具有圖形克作爲其參數的方法

shapetype.draw(g); // he said that g is undefined 

應該怎麼爲了調用函數拉伸(克)初始化克:

public class main extends Applet 
    { 
     Shape shapetype; // shapeClass has 3 subclasses 

     public void init() 
     { 
      super.init(); 

// ask user to choose the type of shape 1-line 2-rectangle 3-oval 
// int choice = the type of shape   
      switch(choice) 
      { 

       case 1: 
       // draw line 
        break; 

       // draw Rectangle 
       case 2: 
       //ask user for x,y,width and height 
       shapetype = new Rectangle(x1,y1,w,h); 
       shapetype.draw(g); // to draw a rectangle 
        break; 

       case 3: 
       // draw Oval 
        break; 

       default: 
        break; 
      } 
     } 

     public void paint(Graphics g) 
     {super.paint(g); } 

    } 
+0

你需要有一個圖形的實例成員,並有內部開關。 –

+0

@sᴜʀᴇsʜᴀᴛᴛᴀ沒有幫助 – moonlight

回答

1

移動繪圖調用到paint方法:

@Overrride // since you're overriding. 
public void paint(Graphics g) { 
    super.paint(g); 

    if(shapetype != null) { 
     shapetype.draw(g); 
    } 
} 

只繪製一次形狀是不夠的,每調用一次paint就會被覆蓋,所以需要重繪。

+0

謝謝你現在的作品 – moonlight