2014-01-13 149 views
1

我有一個類,NewBeautifulKiwi,它有getter和setter。可相容的類型:不能轉換爲

當我嘗試設置:

public void setKiwi(String Kiwi) { 
    this.Kiwi = Kiwi; 
} 

與值從像一個文本字段:

@FXML 
TextField KIWITextField; 
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi() 
    .setKiwi(KIWITextField.getText()); 

我得到的錯誤信息: incopatible類型:不能轉換到NewBeautifulKiwi

這裏是完整的類(此問題的必要提取)

import java.net.URL; 
import java.util.ResourceBundle; 
import javafx.application.Platform; 
import javafx.fxml.FXML; 
import javafx.fxml.Initializable; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.Pane; 
import wakiliproject.Forms.AddNew.DB.NewBeautifulKiwi; 

public class SampleController implements Initializable, ControlledScreen { 

    @FXML 
    TextField KIWITextField; 
    NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi().setKiwi(KIWITextField.getText()); 
} 


import java.io.Serializable; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 

@Entity 
public class NewBeautifulKiwi implements Serializable { 

    @Id 
    @GeneratedValue 
    private int KiwiId; 
    private String Kiwi; 

    public int getKiwiId() { 
     return KiwiId; 
    } 

    public void setKiwiId(int KiwiId) { 
     this.KiwiId = KiwiId; 
    } 

    public String getKiwi() { 
     return Kiwi; 
    } 

    public void setKiwi(String Kiwi) { 
     this.Kiwi = Kiwi; 
    } 
} 

如何將TextField值傳遞給setter?

+0

是否有錯字在你對錯誤信息的描述中,還是在錯誤信息本身中有錯字?如果是後者,我們應該保留你的問題中的錯字,以便其他人可以找到它。 –

回答

1

new NewBeautifulKiwi().setKiwi(KIWITextField.getText());返回值是由setKiwi簽名,這是確定的。

因此,該表達式不會返回任何內容(void),您無法將其分配給變量。您可以拆分兩個語句:

NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi(); 
newBeautifulKiwi.setKiwi(KIWITextField.getText()); 

或者使用流暢的界面風格(我的個人偏好在這種情況下,因爲它可以讓你鏈制定者):

public NewBeautifulKiwi setKiwi(String Kiwi) { 
    this.Kiwi = Kiwi; 
    return this; 
} 

//Now that will compile 
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi().setKiwi(KIWITextField.getText()); 
+0

嗨[assylias](http://stackoverflow.com/users/829571/assylias)。第二種解決方案,流暢的界面,起作用。第一個沒有。我與第二獲得的錯誤是: \t包newBeautifulKiwi不存在, \t 預期, \t包KIWITextField不存在。 \t 可能是什麼問題? – ILikeProgramming

+0

@ user3189827你是否在課堂上在方法中包含了兩行?該錯誤通常是由於缺少方括號或語句未包含在一個文件中的方法或多個類聲明中。 – assylias

+0

哇!謝啦。現在它可以工作。我不得不把這兩個陳述放在一個方法中。 – ILikeProgramming

0
NewBeautifulKiwi newBeautifulKiwi = new 
          NewBeautifulKiwi().setKiwi(KIWITextField.getText()); 

這裏setKiwi是void方法。沒有返回任何東西。您可以按如下

new NewBeautifulKiwi().setKiwi(KIWITextField.getText());` 

如果您setKiwi方法在下列方式您可以使用您當前的代碼更改代碼。 public void setKiwi(String Kiwi)

public NewBeautifulKiwi setKiwi(String Kiwi) { 
this.Kiwi = Kiwi; 
return kiwi; 
} 
0
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi(); 
newBeautifulKiwi.setKiwi(KIWITextField.getText()); 
相關問題