【问题标题】:Java - Vaadin: NativeSelect setValue not workingJava - Vaadin:NativeSelect setValue 不起作用
【发布时间】:2013-06-25 13:12:10
【问题描述】:

我需要为 NativeSelect 设置一个值,设置我希望它在我向 Select 字段添加项目时显示的元素。 我可以假设这是我应该完成的一个很好的例子:

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;
    }
}
}

我的问题是值设置不正确,结果总是为空。 对于这个问题有什么建议吗?

【问题讨论】:

    标签: java select vaadin setvalue


    【解决方案1】:

    在 Java 中,hashCode()equals() 必须一致:

    只要 a.equals(b),则 a.hashCode() 必须与 b.hashCode() 相同。

    请参阅javadoc for Object#equals(Object)this StackOverflow question 了解更多讨论和推理。

    因此,在您的示例中,您需要使用 name 和 id 在 Customer 上实现 hashCode()(我的 IDE 生成了此代码)。

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

    【讨论】:

    • 你正式成为我的偶像! :) 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多