2013-06-25 76 views
1

我需要爲NativeSelect設置一個值,設置我希望顯示的元素後,我將項目添加到Select字段。 我可以假設這是一個很好的例子,因爲我應該完成的任務:Java - Vaadin:NativeSelect setValue無法正常工作

public class TestselectUI extends UI { 
@Override 
protected void init(VaadinRequest request) { 
    final VerticalLayout layout = new VerticalLayout(); 
    layout.setMargin(true); 
    setContent(layout); 

    NativeSelect sel = new NativeSelect(); 
    Customer c1 = new Customer("1", "Pippo"); 
    Customer c2 = new Customer("2", "Pluto"); 
    Customer c3 = new Customer("3", "Paperino"); 
    Customer c4 = new Customer("4", "Pantera"); 
    Customer c5 = new Customer("5", "Panda"); 

    sel.addItem(c1); 
    sel.addItem(c2); 
    sel.addItem(c3); 
    sel.addItem(c4); 
    sel.addItem(c5); 

    Customer test = new Customer(c4.id, c4.name); 
    sel.setValue(test); 

    layout.addComponent(sel); 
} 

private class Customer { 
    public String id; 
    public String name; 

    /** 
    * @param id 
    * @param name 
    */ 
    public Customer(String id, String name) { 
     super(); 
     this.id = id; 
     this.name = name; 
    } 

    @Override 
    public String toString() { 
     return this.name; 
    } 

    @Override 
    public boolean equals(final Object object) { 
     // return true if it is the same instance 
     if (this == object) { 
      return true; 
     } 
     // equals takes an Object, ensure we compare apples with apples 
     if (!(object instanceof Customer)) { 
      return false; 
     } 
     final Customer other = (Customer) object; 

     // implies if EITHER instance's name is null we don't consider them equal 
     if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { 
      return false; 
     } 

     return true; 
    } 
} 
} 

我的問題是,在沒有設置正確,原來一直爲空值。 這個問題的任何提示?

回答

1

在Java中,hashCode()equals()必須是一致的:

每當a.equals(B),然後a.hashCode()必須是相同b.hashCode()。

查看javadoc for Object#equals(Object)this StackOverflow question瞭解更多討論和推理。

因此,在您的示例中,您需要使用name和id(我的IDE生成此代碼)在Customer上實現hashCode()。

public class Customer { 
    [...] 

    @Override 
    public int hashCode() { 
    int result = id != null ? id.hashCode() : 0; 
    result = 31 * result + (name != null ? name.hashCode() : 0); 
    return result; 
    } 
} 
+0

你是我的偶像! :) 非常感謝! –