Thursday, June 23, 2016

72. Observable List

Often we need a list of data to connect to a UI element.


The ObservableList class is used to change a list and its listener prints the change, in a TextArea. The TextArea is non-editable, since we only use it to display information.


package ex72;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import static javafx.collections.ListChangeListener.Change;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
 
public class Ex72 extends Application {
    
    private final String style =
           "-fx-font-family: Georgia; -fx-font-size: 24;"
         + "-fx-text-fill: purple; -fx-background-color: greenyellow;";
    private TextArea textArea;
    
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        textArea = new TextArea();
        textArea.setStyle(style);
        textArea.setPadding(new Insets(10));
        textArea.setPrefRowCount(30);
        textArea.setPrefColumnCount(15);
        textArea.setEditable(false);
        
        final List list = Arrays.asList("-1", "-2");
        ObservableList obsList = 
                FXCollections.observableArrayList(list);
        
        appendText("Initial obsList", false);
        appendText(obsList.toString(), true);
 
        obsList.addListener((Change change) -> {
            appendText(change.toString(), false);
            appendText(change.getList().toString(), true);
        });
        
        obsList.addAll("1","2","3");
        obsList.add("4");
        obsList.add(0, "0");
        obsList.addAll("4", "5");
        obsList.set(1, "One");
        obsList.removeAll("3", "4");
        obsList.remove("1");
        obsList.clear();
        
        VBox vbox = new VBox(textArea);
        
        Scene scene = new Scene(vbox);
        primaryStage.setTitle("Example 72. Observable List");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private void appendText(String text, boolean endNewLine) {
        if (endNewLine) textArea.appendText("\n" + text + "\n");
        else textArea.appendText("\n" + text);
    }
}

This is the output:


No comments:

Post a Comment