2014-12-05 145 views
0
class Robot extends Canvas 
{ 
    public Robot() //constructor method - sets up the class 
    { 
     setSize(800,600); 
     setBackground(Color.WHITE);  
     setVisible(true); 
    } 

    public void paint(Graphics window) 
    { 
     window.setColor(Color.BLUE); 
     window.drawString("Robot LAB ", 35, 35); 




     //call head method 

     //call other methods 

    } 

    public void head(Graphics window) 
    { 
     window.setColor(Color.YELLOW); 
     window.fillRect(300, 100, 200, 100); 


     //add more code here 

    } 

我該如何稱呼頭部方法?帶參數的呼叫方法

我試過多次,但我似乎無法得到它。

head(); window.head();沒有爲我工作?

對不起,我對此很新。

+0

'head(window);'? – Thilo 2014-12-05 00:49:28

+0

謝謝!頭(窗口);爲我工作,但我可以知道你爲什麼把窗口放在括號內?括號內通常會出現什麼內容? – prora 2014-12-05 00:51:24

回答

0

您需要使用

head(window); 

這是你剛纔怎麼調用一個方法在Java參數(和大多數其他語言),你把參數在後面的括號以逗號分隔的列表方法名稱。請注意,甚至在沒有任何參數的情況下,這些缺口仍然存在。

methodWithNoParameters(); 
someOtherObject.methodWithNoParameters(); 
this.methodWithOneParameter("foo"); 
SomeClass.staticMethodWithFiveParameters(1,two,3,4, "five"); 

參數的數量,順序和類型必須與方法聲明的形式參數相匹配。在你的情況下,public void(Graphics window)意味着只有一個。

最後,如果您只從paint(而不是從課程本身之外)調用此方法,則應該使此方法爲private