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

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

by Witold Szczerba :: Rate this Message:

Reply to Author | View in Thread

2009/7/3 janne mattila <jannepostilistat@...>:
> MyBean {
>     private List<Integer> choices;
>     private Integer selected;

> [...] I am wondering however if this is the easiest way.

Try this: change your List<Integer> choices into:
private final ObservableList<List> choices =
 ObservbleCollections.observableList(
  new ArrayList<Integer>());

As you see, this list is final, you will never change it. Now bind
your dropdown to this list. It does not matter if you populate this
list before or after binding. You are free to add/remove elements
whenever you want and dropdown will be notified/refreshed.


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

This code is just incorrect.
a) You get the list object.
b) You add element into this list.
c) You invoke setChoices with list object which is the same object you
got in step (a). I mean this is physically the same object. This step
does nothing. It looks like it is setting something, but all it does
is nothing :)

Try the way with observable list I described at the beginning. I
always do it this way. In my program, when I create a form and load
new data from server, I always do it like this:

List<Something> newData = ...;
myListOfSomething.clear();
myListOfSomething.addAll(newData);

To be more precise, new data are fetched in #doInBackground method of
SwingWorker, then it is passed to #done, and observable lists are
reloaded on the Event Dispatch Thread, but this applies to Swing only.

Regards,
Witold Szczerba

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