我正在尝试构建一个文本编辑器。我正在使用 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 - JavaFX:在 ListView 中换行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53493111/