我有一个Swing JComboBox,里面填充了Person类型的对象列表,其中Person如下:
public class Person implements Comparable<Person> {
private String login;
private String personFirstName;
private String personLastName;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPersonFirstName() {
return personFirstName;
}
public void setPersonFirstName(String personFirstName) {
this.personFirstName = personFirstName;
}
public String getPersonLastName() {
return personLastName;
}
public void setPersonLastName(String personLastName) {
this.personLastName = personLastName;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Person) {
Person person = (Person) obj;
if (this.getPersonFirstName() == null) {
if (person.getPersonFirstName() != null)
return false;
} else {
if (!this.getPersonFirstName().equals(person.getPersonFirstName()))
return false;
}
if (this.getPersonLastName() == null) {
if (person.getPersonLastName() != null)
return false;
} else {
if (!this.getPersonLastName().equals(person.getPersonLastName()))
return false;
}
return true;
} else
return false;
}
@Override
public int compareTo(Person p) {
if (this.getLogin() != null) {
return this.getLogin().compareTo(p.getLogin());
}
return -1;
}
@Override
// the login is unique for every user.
public int hashCode() {
if (this.getLogin() != null) {
return this.getLogin().hashCode() ^ 3;
}
return 0;
}
}
问题是,我在我的combobox 3用户上分别有 login - firstName lastName ,如下所示:
劳伦斯 - 劳伦斯史蒂文斯
lawrencev - lawrence victor
lawrencec - 劳伦斯米勒
当我选择其中任何一个用户时
userCombobox.getSelectedItem()
总是返回劳伦斯 - 劳伦斯史蒂文斯
答案 0 :(得分:0)
Person类似乎有效。问题可能在于您的其他代码。如果您使用的是Eclipse,那么请考虑使用hashCode()和equals()的内置生成器。 Eclipse还生成一个好的toString()用于调试。我的短测试工作正常(所选项目在更改时打印):
public static void main(String[] args) {
JFrame frame = new JFrame("Lawrence");
Person[] persons = new Person[] { //
new Person("lawrence", "lawrence", "stevens"), //
new Person("lawrencev", "lawrence", "victor"), //
new Person("lawrencec", "lawrence", "miller") };
JComboBox<Person> comboBox = new JComboBox<>(persons);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(">" + comboBox.getSelectedItem());
}
});
frame.add(comboBox);
frame.pack();
frame.setVisible(true);
}
在Person中添加了这个构造函数:
public Person(String login, String personFirstName, String personLastName) {
super();
this.login = login;
this.personFirstName = personFirstName;
this.personLastName = personLastName;
}