The following code snippet listen to changes in rectangles (a list of rectangles ) and prints event is invoked. on screen whenever a Rectangle object is added to or removed from rectangles.
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class test2 {
public static void main(String[] args) {
Rectangle rectangle=new Rectangle(0,0,1,1);
ObservableList<Rectangle> rectangles = FXCollections.observableArrayList();
rectangles.addListener((ListChangeListener<Rectangle>) change ->
System.out.println("event is invoked."));
rectangles.addAll(rectangle);
}
}
My question is whether it is possible to listen to changes in the objects in rectangles rather than listening to adding to or removing from rectangles. For example, the event should be invoked when I change the fill color of a Rectangle object in rectangles. I tried the following code (added a line of rectangle.setFill(new Color(1,0,0,0.5));) and expected to have event is invoked. printed twice, but it did not work.
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class test2 {
public static void main(String[] args) {
Rectangle rectangle=new Rectangle(0,0,1,1);
ObservableList<Rectangle> rectangles = FXCollections.observableArrayList();
rectangles.addListener((ListChangeListener<Rectangle>) change ->
System.out.println("event is invoked."));
rectangles.addAll(rectangle);
rectangle.setFill(new Color(1,0,0,0.5));
}
}