« Return to Thread: binding a dropdown to a List, and adding new values to List

binding a dropdown to a List, and adding new values to List

by janneefef :: Rate this Message:

Reply to Author | View in Thread

I created a form with a dropdown which displays integer values 1....n. This is bound to two bean properties using beansbinding:

elements: MyBean.choices
selectedItem: MyBean.selected

MyBean {
    private List<Integer> choices;
    private Integer selected;

This works fine. I'm wondering how to implement adding new choices though. My setChoices() looks like:


    public void setChoices(List<Integer> choices) {
        List<Integer> old = this. choices;
        this. choices = choices;
        firePropertyChange("choices", old, choices);
        System.out.println("fired change: " + old + ", " + choices);
    }

and the method which adds a new choice:

    public void addChoice() {
        System.out.println("adding loadchoice");
        List<Integer> newChoices = new ArrayList<Integer>(getChoices());
        newChoices .add(newChoices .size() + 1);
        setLoadNumberChoices(newChoices );
    }

This works too....I am wondering however if this is the easiest way. It seems like a lot of work to create a new copy of the List each time one item is modified, especially since Lists can contain much more complex objects than Integers. Isn't there a way to just add a new choice to the original List and have beansbinding notice this change? 

Tried like this but results is an empty dropdown for some reason:

    public void addChoice() {
        System.out.println("adding choice");
        choices.add(choices.size() + 1);
        setChoices(choices);
    }

 « Return to Thread: binding a dropdown to a List, and adding new values to List