Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't know if I correctly understood your question, but I will try to answer it :-). </p> <p>The thing is, once a ObservableList (javafx.collections) object does not store some kind of "selected" index state, why do we should bind another integer to it?</p> <p>I think, in this case, your code should be responsible for store the "selected" index state and expose it to a client code. If this is what you are looking for, I suggest you have three attributes to deal with it:</p> <pre><code>public class ListSelection&lt;T&gt; { private ObservableList&lt;T&gt; items = FXCollections.observableArrayList(new ArrayList&lt;T&gt;()); private ObjectProperty&lt;T&gt; selectedItem = new SimpleObjectProperty&lt;&gt;(); private IntegerProperty selectedIndex = new SimpleIntegerProperty(0); } </code></pre> <p>The selected element can be controlled using the <code>selectedIndex</code> attribute. </p> <p>Then, create a bind to the <code>selectedItem</code>, to "automatically" update it when <code>selectedIndex</code> change:</p> <pre><code>selectedItem.bind( when(isEmpty(items)) .then(new SimpleObjectProperty&lt;T&gt;()) .otherwise(valueAt(items, selectedIndex)) ); </code></pre> <p><code>Bindings</code> should have been imported statically:</p> <pre><code>import static javafx.beans.binding.Bindings.*; </code></pre> <p>Notice the use of method <code>Bindings.valueAt(ObservableList&lt;E&gt; list, ObservableIntegerValue index)</code>. It creates a bind to the <code>list.get(index.getValue())</code> element.</p> <p>Finally, you can use it like this:</p> <pre><code>ListSelection&lt;String&gt; selection = new ListSelection&lt;&gt;(); Label label = new Label(); List&lt;String&gt; weekDays = Arrays.asList("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"); selection.getItems().addAll(weekDays); label.textProperty().bind(selection.selectedItemProperty()); </code></pre> <p>I also suggest you to take a look to <code>javafx.scene.control.SelectionModel</code> class and its subclasses (eg. <code>javafx.scene.control.SingleSelectionModel</code>). Maybe, it could be easier to extend some of them.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload