↓こんな感じのTwitterのタイムラインみたいなリストを作ってみる。

まず、このデータのクラスを作る。
public class Article {
private String user; // ユーザ名
private String comment; // コメント
private Image image; // アイコン
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public Article(Image image, String user, String comment) {
this.user = user;
this.comment = comment;
this.image = image;
}
}
セルを作るクラスを作る。コンストラクタでコントロールやコンテナを作成して、updateItem()で値だけをできるだで更新する。図のようにHBoxにImageViewとVBoxを追加して、VBoxにはユーザ名用のTextとコメント用のTextを追加する。
public class ArticleCell extends ListCell<Article> {
private final HBox hbox;
private final ImageView imageView;
private final VBox vbox;
private final Text user;
private final Text comment;
public ArticleCell() {
hbox = new HBox(5);
imageView = new ImageView();
imageView.setFitWidth(64);
imageView.setFitHeight(64);
vbox = new VBox(5);
user = new Text();
user.setFont(new Font("System Bold", 18));
comment = new Text();
VBox.setVgrow(user, Priority.NEVER);
VBox.setVgrow(comment, Priority.ALWAYS);
HBox.setHgrow(imageView, Priority.NEVER);
HBox.setHgrow(vbox, Priority.ALWAYS);
vbox.getChildren().addAll(user, comment);
hbox.getChildren().addAll(imageView, vbox);
// ユーザ名、コメントをVBoxの幅-5になるようにバインドしとく
user.wrappingWidthProperty().bind(vbox.widthProperty().subtract(5));
comment.wrappingWidthProperty().bind(vbox.widthProperty().subtract(5));
}
@Override
protected void updateItem(Article item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
imageView.setImage(item.getImage());
user.setText(item.getUser());
comment.setText(item.getComment());
setGraphic(hbox);
}
}
}
カスタムセルを作るようにFXMLDocumentControllerのinitializeで
listView.setCellFactory(param -> new ArticleCell());
をしておく。
ソースおいておく。
コメント