如何在 Java 不兼容类型中为该函数赋值?
public class CustomerInfo implements Serializable {
private static final long serialVersionUID = 9083257536541L;
protected String id;
protected String searchkey;
protected String taxid;
protected String name;
protected String postal;
/** Creates a new instance of UserInfoBasic */
public CustomerInfo(String id) {
this.id = id;
this.searchkey = null;
this.taxid = null;
this.name = null;
this.postal = null;
}
public String getId() {
return id;
}
public String getTaxid() {
return taxid;
}
public void setTaxid(String taxid) {
this.taxid = taxid;
}
public String getSearchkey() {
return searchkey;
}
public void setSearchkey(String searchkey) {
this.searchkey = searchkey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPostal() {
return postal;
}
public void setPostal(String postal) {
this.postal = postal;
}
public String printTaxid() {
return StringUtils.encodeXML(taxid);
}
public String printName() {
return StringUtils.encodeXML(name);
}
@Override
public String toString() {
return getName();
}
}
private CustomerInfo selectedCustomer;
public CustomerInfo getSelectedCustomer() {
// construct a CustomerInfo from the data in your String
return selectedCustomer;
}
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
selectedCustomer = (CustomerInfo) jListCustomers.getSelectedValue();
//test code
String testing = m_jtxtName.getText();
System.out.println("Now the selectedCustomer is dispayed!");
System.out.println(selectedCustomer);
System.out.println(testing);
//test code
dispose();
}
在上面显示的代码中,我需要将字符串测试值分配给 selectedCustomer
。我该如何分配值(value)?这是我得到的错误:
selectedCustomer = m_jtxtName.getText();
incompatible types
required: CustomerInfo
found: String
最佳答案
你不能!!!
selectedCustomer
是 CustomerInfo
类型的对象。
m_jtxtName.getText()
返回一个 String
您不能将字符串分配给 CustomerInfo。
可能你需要做这样的事情:
int id = 1; //Or whatever new id you have.
String name = m_jtxtName.getText();
selectedCustomer = new CustomerInfo(name); //or whatever id you have.
selectedCustomer.setName(name); //or whatever name you have.
编辑:
您的类(class)中缺少某些内容。它要么需要 setter 方法(它现在只有 getter,因此你不能将其他属性设置为名称等),要么它需要一个带有四个参数的构造函数,例如:
public CustomerInfo(String id, String searchKey, String taxid, String name, String postal) {
this.id = id;
this.searchKey = searchKey;
// etc
在这种情况下,您的屏幕中可能有六个 jtextfields,因此用户可以填写所有字段并通过将所有参数传递给构造函数来创建 Customerinfo 对象。
关于java - 如何在 java 不兼容类型中为这个函数赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16789173/