如何在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
。我该如何分配价值?这是我得到的错误:
selectedCustomer = m_jtxtName.getText();
incompatible types
required: CustomerInfo
found: String
答案 0 :(得分:2)
你不能!!!
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.
编辑:
你班上缺少一些东西。它需要setter方法(它现在只有getter,所以你不能将其他属性设置为名称等)或者它需要一个带有四个参数的构造函数,如:
public CustomerInfo(String id, String searchKey, String taxid, String name, String postal) {
this.id = id;
this.searchKey = searchKey;
// etc
在这种情况下,您的屏幕可能有六个jtextfields,因此te用户可以填充所有字段,并通过将所有参数传递给构造函数来创建Customerinfo对象。
答案 1 :(得分:1)
你不能通过简单地将一个字符串转换为CustomerInfo
对象来实现,但你可以扩展你的CustomerInfo
,但你可以尝试这样的事情:
public class CustomerInfo {
[...]
public static CustomerInfo createCustomerInfo(String data) {
// construct a CustomerInfo from the data in your String
return createdCustomerInfo;
}
}
我不知道你在String中有什么数据,所以我不能给你一个如何实现这个的建议。例如如果是ID,您可以使用它从数据库或类似的东西中检索CustomerInfo。