Why use the Observablelist?

Asked

Viewed 762 times

3

I have a theoretical doubt. I was studying Javafx and 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, adding each Node to the Observablelist instead of adding it to the Group itself. I noticed that changes in the Observablelist, since Observablelist receives an Observablelist from the Group, implies changes in the root Group Node. I’d like to know Why use Observablelist...?

1 answer

3


Usually the books about Javafx present in their codes the reduced version of the expression that caused you doubts, 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 noted, the return of the method getChildren() is precisely an Observablelist of Nodes. The author only thought it was right to assign a variable to reference the list of container nodes and, as a reference (save the address of the list in memory), to change list means changing the list it references.

inserir a descrição da imagem aqui

This option can be due to style or didactic issues (I believe it wants to show that each component of the Container is stored in a list).

I will give an example to facilitate understanding:

// Livros para um público iniciante podem apresentar a informação assim
public int greaterThan(int a, int b){
    int result = 0;
    if(a > b){
        result = 1;
    }
    return result;
}

// Para um público mais avançado pode aparecer algo desse tipo
public int greaterThan(int a, int b){
    return (a > b) ? 1 : 0;    
}

Some students easily recognize that the two greaterThan functions are saying the same thing, so for these students it is indifferent. But for beginners the "verbose" version is more profitable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.