TableView单元格自动换行
问题描述:
我想创建一个单元格,在其中可以包装文本,这是到目前为止我的解决方案:
I want to create a cell where i can wrap the text this is my solution what i've got so far:
tableCol.setCellFactory(param -> {
return new TableCell<Data, String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setStyle("");
} else {
Text text = new Text(item);
text.setStyle("-fx-padding: 5px 30px 5px 5px;"
+ "-fx-text-alignment:justify;");
text.setWrappingWidth(param.getPrefWidth() - 35);
System.out.println(text.getLayoutBounds().getHeight()+10);//117
//setPrefHeight(text.getLayoutBounds().getHeight()+10); -----> This is not working somehow
setPrefHeight(117);
setGraphic(text);
}
}
};
});
这是可行的,但问题是我必须对PREFHEIGHT
进行硬编码.我真的不明白为什么这条线不起作用:
This one is working but the issue is that i had to hard coded the PREFHEIGHT
. I don't really understand why this line is not working:
setPrefHeight(text.getLayoutBounds().getHeight()+10)
非常感谢您的帮助.
答
更新
应为TableRow
指定高度:
package com.company;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
ObservableList<Integer> values = FXCollections.observableArrayList();
values.addAll(1, 2, 3);
TableColumn<Integer, Integer> tableColumn = new TableColumn<>("Column1");
tableColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));
tableColumn.setCellFactory(param -> {
return new TableCell<Integer, Integer>() {
@Override
protected void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (item == null) {
setText("");
} else {
setText(item.toString());
}
}
};
});
TableView<Integer> tableView = new TableView<>();
tableView.setFixedCellSize(Region.USE_COMPUTED_SIZE);
tableView.getColumns().add(tableColumn);
tableView.setItems(values);
tableView.setRowFactory(param -> {
return new TableRow() {
@Override
public void updateIndex(int i) {
super.updateIndex(i);
setMinHeight(50 * i);
}
};
});
Scene scene = new Scene(tableView, 320, 480);
primaryStage.setScene(scene);
primaryStage.show();
}
}