Search code examples
javajavafxfxml

FXML ListView, I can't add my ObservableArrayList<Pane> to it


I'm writing a messenger in Java and FXML and I want to show all the current chats of the user on a ListView(chatBar). My chats are in an ObservableArrayList but I still can't add the values to the ListView.

public void fillChatBar() {
    ArrayList<Chat> chats = db.getAllInvolvedChats(user.getUserID());

    ObservableList<Pane> chatHolder = FXCollections.observableArrayList();

    chats.forEach(chat -> {
        Pane chatPane = new Pane();
        Label chatName = new Label();
        chatName.setText(chat.getOpponent(user.getUserID()).getUsername());
        chatPane.getChildren().add(chatName);
        chatPane.getChildren().add(new ImageView(chat.getOpponent(user.getUserID()).getProfileImage()));

        chatHolder.add(chatPane);
    });

    chatBar.setItems(chatHolder);
}

I get no error messages or exceptions. It just won't show.


Solution

  • the problem is that you misunderstood the usage of ListView ;)

    The items that are stored in a ListView are no cell-views but models. Internally the ListView creates cells that represents the model items and shows them on screen. You can try this by simply creating a ListView<String> and add a list of Strings to the items. You will see labels that shows the String values omg the screen. For such basic datatypes like String your ListView automatically creates cell-views to hat makes sense. For more complexe model types (like a list of custom models) you need to write your own cell-view factory (or overwrite toString() in your model class). See this tutorial as a first example to work with Strings. A more complexe example can be found here.