JavaFX:在 ListView 中包装文本
JavaFX: Wrapping text in ListView
我正在尝试构建一个文本编辑器。我正在使用 ListView 来存储评论。我希望字符串自动换行,而不必水平滚动它,这样长字符串就不必滚动太多。
请建议一种将字符串包装在 ListView 中的方法。
编辑 1:
我的 ListView 是从 FXML 初始化的
编辑 2:
我终于可以让初始化正常工作了。
您所要做的就是覆盖默认单元格,使用您自己的自定义单元格,其宽度为 List
的宽度,并且还允许文本换行。该实现基于 Cell
是 Labled
的事实
list.setCellFactory(param -> new ListCell<DataModel>(){
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item==null) {
setGraphic(null);
setText(null);
// other stuff to do...
}else{
// set the width's
setMinWidth(param.getWidth());
setMaxWidth(param.getWidth());
setPrefWidth(param.getWidth());
// allow wrapping
setWrapText(true);
setText(item.toString());
}
}
});
我正在尝试构建一个文本编辑器。我正在使用 ListView 来存储评论。我希望字符串自动换行,而不必水平滚动它,这样长字符串就不必滚动太多。 请建议一种将字符串包装在 ListView 中的方法。
编辑 1: 我的 ListView 是从 FXML 初始化的 编辑 2: 我终于可以让初始化正常工作了。
您所要做的就是覆盖默认单元格,使用您自己的自定义单元格,其宽度为 List
的宽度,并且还允许文本换行。该实现基于 Cell
是 Labled
list.setCellFactory(param -> new ListCell<DataModel>(){
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item==null) {
setGraphic(null);
setText(null);
// other stuff to do...
}else{
// set the width's
setMinWidth(param.getWidth());
setMaxWidth(param.getWidth());
setPrefWidth(param.getWidth());
// allow wrapping
setWrapText(true);
setText(item.toString());
}
}
});