java - How to bind the position in a List to an attribute of that element? -


i have observablelist<myelement> list = fxcollections.observablearraylist();

public class myelement {   private integerproperty position;//with getter   //[...]    //somewhere in constructor taking list argument   position.bind(list.indexof(this)); } 

now i'd bind myelement.position actual position in list i.e. if position changes in list (for instance drag , drop in gui or else) want position property updated automatically.

is possible? can make bidirectional binding between these values?

i don't know if correctly understood question, try answer :-).

the thing is, once observablelist (javafx.collections) object not store kind of "selected" index state, why should bind integer it?

i think, in case, code should responsible store "selected" index state , expose client code. if looking for, suggest have 3 attributes deal it:

public class listselection<t> {     private observablelist<t> items = fxcollections.observablearraylist(new arraylist<t>());     private objectproperty<t> selecteditem = new simpleobjectproperty<>();     private integerproperty selectedindex = new simpleintegerproperty(0); } 

the selected element can controlled using selectedindex attribute.

then, create bind selecteditem, "automatically" update when selectedindex change:

selecteditem.bind(     when(isempty(items))         .then(new simpleobjectproperty<t>())         .otherwise(valueat(items, selectedindex)) ); 

bindings should have been imported statically:

import static javafx.beans.binding.bindings.*; 

notice use of method bindings.valueat(observablelist<e> list, observableintegervalue index). creates bind list.get(index.getvalue()) element.

finally, can use this:

listselection<string> selection = new listselection<>(); label label = new label(); list<string> weekdays = arrays.aslist("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");  selection.getitems().addall(weekdays); label.textproperty().bind(selection.selecteditemproperty()); 

i suggest take javafx.scene.control.selectionmodel class , subclasses (eg. javafx.scene.control.singleselectionmodel). maybe, easier extend of them.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -