2016-03-19 15 views
0

這個問題已經被問過,但即使閱讀後:Java中,獲得一套方法

Java "Get" and "Set" Methods

Java Get/Set method returns null

而更多的我還是不知道如何解決我的問題。

當使用另一個類的get方法訪問類中的變量時,我收到值爲null。

如何接收我的正確值而不是null?


這是我試圖讓我的變量從(不是所有東西都包括在內)的類。

public class RLS_character_panel extends javax.swing.JPanel implements ActionListener, ItemListener { 

    private String name1 = "hello"; 

    public String getName1() { 
     return name1; 
    } 

    public void setName1(String name1) { 
     this.name1 = name1; 
    } 

} 

這是我嘗試獲取值的類。該類擴展了JFrame,以便我可以添加一個顯示變量的JPanel。 (JPanel是另一個類,名爲:RLS_strid_panel,它被添加到這個幀上)。

public class RLS_strid_java extends JFrame { 

    RLS_character_panel test = new RLS_character_panel(); 

    String name1 = test.getName1(); 

    RLS_strid_panel p = new RLS_strid_panel(namn1); 

    // constructor 
    public RLS_strid_java(String titel) { 
     super(titel); 
     this.setSize(1000, 772); 
     this.setVisible(true); 
     this.setResizable(false); 
     this.add(p); 
    } 
} 

JPanel中顯示爲空。

+4

當你通過代碼在調試器步驟,可以你看到哪個值是'null'? –

+4

哦,人,命名!尊重Java命名約定,併爲您的課程提供有意義的名稱。並向我們​​展示顯示值的代碼。 –

+0

你如何構建「外部」RLS_strid_java? 「subpanel」'p'看起來很好,但是你怎樣從類外部調用'RLS_strid_java'的構造函數? –

回答

3

爲了理解get和set,它都與變量在不同類之間傳遞的方式有關。

get方法用於從類中獲取或檢索特定的變量值。

設置值用於存儲變量。

get和set的全部點是相應地檢索和存儲數據值。

我在這個舊項目中做了什麼是我有一個用戶類與我的服務器類中使用我的get和set方法。

User類的get set方法:

public int getuserID() 
    { 
     //getting the userID variable instance 
     return userID; 
    } 
    public String getfirstName() 
    { 
     //getting the firstName variable instance 
     return firstName; 
    } 
    public String getlastName() 
    { 
     //getting the lastName variable instance 
     return lastName; 
    } 
    public int getage() 
    { 
     //getting the age variable instance 
     return age; 
    } 

    public void setuserID(int userID) 
    { 
     //setting the userID variable value 
     this.userID = userID; 
    } 
    public void setfirstName(String firstName) 
    { 
     //setting the firstName variable text 
     this.firstName = firstName; 
    } 
    public void setlastName(String lastName) 
    { 
     //setting the lastName variable text 
     this.lastName = lastName; 
    } 
    public void setage(int age) 
    { 
     //setting the age variable value 
     this.age = age; 
    } 
} 

那麼這是在run()方法來實現我的服務器類,如下所示:

//creates user object 
       User use = new User(userID, firstName, lastName, age); 
       //Mutator methods to set user objects 
       use.setuserID(userID); 
       use.setlastName(lastName); 
       use.setfirstName(firstName);    
       use.setage(age);