Why use ObservableList?

3

I have a theoretical doubt. I was studying JavaFX and I do not know what the function of ObservableList in this case:

 public void start(Stage stage) {
        //Creating a Text object
        Text text = new Text();

        //Setting font to the text
        text.setFont(new Font(45));

        //setting the position of the text
        text.setX(50);
        text.setY(150);

        //Setting the text to be added.
        text.setText("Welcome to Tutorialspoint");

        //Creating a Group object
        Group root = new Group();

        //Retrieving the observable list object
        ObservableList list = root.getChildren();

        //Setting the text object as a node to the group object
        list.add(text);

        //Creating a scene object
        Scene scene = new Scene(root, 600, 300);

        //Setting title to the Stage
        stage.setTitle("Sample Application");

        //Adding scene to the stage
        stage.setScene(scene);

        //Displaying the contents of the stage
        stage.show();

    }

The book I'm studying javaFx did so, added each Node in the ObservableList instead of adding it to the Group itself. I noticed that changes in the ObservableList, since ObservableList receives from the Group an ObservableList, implies changes in the Root Node Group. I would like to know Why to use ObservableList ...?

    
asked by anonymous 30.06.2017 / 15:31

1 answer

3

JavaFX books usually have the reduced version of the expression that caused you doubts in your code, putting it this way:

Group root = new Group();
root.getChildren().add(text);

// O formato abaixo equivale ao código acima
Group root = new Group();
ObservableList list = root.getChildren();
list.add(text);

However, as you well observed, the method returns getChildren () is just an ObservableList of Nodes . The author just found it good to assign a variable to refer to the list of nodes in the container and, because it is a reference (stores the address of the list in memory), changing list means changing the list that it references .

Thisoptionmaybeforthesakeofstyleorforinstructionalpurposes(IbelievehewantstoshowthateachContainercomponentisstoredinalist).

I'llgiveyouanexampletomakeiteasiertounderstand:

//LivrosparaumpúblicoiniciantepodemapresentarainformaçãoassimpublicintgreaterThan(inta,intb){intresult=0;if(a>b){result=1;}returnresult;}//ParaumpúblicomaisavançadopodeapareceralgodessetipopublicintgreaterThan(inta,intb){return(a>b)?1:0;}

SomestudentseasilyrecognizethatthetwogreaterThanfunctionsaresayingthesamething,soforthesestudentsitisindifferent.Butforbeginnersthe"verbose" version is more useful.

    
30.07.2017 / 17:45