我有一个类NewBeautifulKiwi
,它具有getter和setter方法。
当我尝试设置以下内容时:
public void setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
}
来自TextField的值,例如:
@FXML
TextField KIWITextField;
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi()
.setKiwi(KIWITextField.getText());
我收到错误消息:
不兼容的类型:无法转换为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值传递给设置器?
最佳答案
new NewBeautifulKiwi().setKiwi(KIWITextField.getText());
的返回值由setKiwi
的签名确定,即:public void setKiwi(String Kiwi)
。
因此该表达式不返回任何内容(无效),并且您无法将其分配给变量。您可以拆分两个语句:
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());