FXML ListView,我无法将 ObservableArrayList<Pane> 添加到其中
FXML ListView, I can't add my ObservableArrayList<Pane> to it
我正在用 Java 和 FXML 编写一个 Messenger,我想在 ListView
(chatBar) 上显示用户的所有当前聊天记录。我的聊天记录在 ObservableArrayList
中,但我仍然无法将值添加到 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);
}
我没有收到任何错误消息或异常。就是不显示。
问题是你误解了 ListView
的用法 ;)
存储在ListView
中的items
不是cell-views
而是模型。 ListView
在内部创建代表模型项目的单元格并将它们显示在屏幕上。您可以通过简单地创建 ListView<String>
并向项目添加字符串列表来尝试此操作。您将在屏幕上看到显示 String
值的标签。对于像 String
这样的基本数据类型,您的 ListView
自动创建 cell-views 是有意义的。对于更复杂的模型类型(如自定义模型列表),您需要编写自己的 cell-view 工厂(或在您的模型 class 中覆盖 toString()
)。参见 this tutorial as a first example to work with Strings. A more complexe example can be found here。
我正在用 Java 和 FXML 编写一个 Messenger,我想在 ListView
(chatBar) 上显示用户的所有当前聊天记录。我的聊天记录在 ObservableArrayList
中,但我仍然无法将值添加到 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);
}
我没有收到任何错误消息或异常。就是不显示。
问题是你误解了 ListView
的用法 ;)
存储在ListView
中的items
不是cell-views
而是模型。 ListView
在内部创建代表模型项目的单元格并将它们显示在屏幕上。您可以通过简单地创建 ListView<String>
并向项目添加字符串列表来尝试此操作。您将在屏幕上看到显示 String
值的标签。对于像 String
这样的基本数据类型,您的 ListView
自动创建 cell-views 是有意义的。对于更复杂的模型类型(如自定义模型列表),您需要编写自己的 cell-view 工厂(或在您的模型 class 中覆盖 toString()
)。参见 this tutorial as a first example to work with Strings. A more complexe example can be found here。