不兼容的类型:无法转换为

时间:2014-01-13 10:29:01

标签: java javafx

我有一个班级NewBeautifulKiwi,有吸气剂和制定者。

当我尝试设置:

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值传递给setter?

3 个答案:

答案 0 :(得分:1)

new NewBeautifulKiwi().setKiwi(KIWITextField.getText());的返回值取决于setKiwi的签名,即:public void setKiwi(String Kiwi)

因此表达式不返回任何内容(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());

答案 1 :(得分:0)

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

这里setKiwi是无效方法。没有回复任何东西。您可以按如下方式更改代码

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

如果按照以下方式使用setKiwi方法,则可以使用当前代码。

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

答案 2 :(得分:0)

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