我不会将格式化文本放在 JavaFX 表中。首先,我试图嵌入一个 Webview,但我遇到了单元格高度问题。这似乎是 JavafX 中的一项任务功能(请参阅:Java FX: TableView - display simple HTML)。
根据此处的建议,我尝试嵌入 TextFlow。然而,TabelCell 的大小再次不正确。我希望行的高度一样大,单元格的内容适合其中。更改列宽应导致更改行高。
这是我的最小运行示例。
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class TableViewSample extends Application {
private final ObservableList<MyData> data = FXCollections.observableArrayList(new MyData(1L), new MyData(3L), new MyData(2L), new MyData(4L), new MyData(1L));
public static void main(final String[] args) {
launch(args);
}
@Override
public void start(final Stage stage) {
final Scene scene = new Scene(new Group());
TableView<MyData> table = new TableView<>();
final TableColumn<MyData, Long> nameCol = new TableColumn("So So");
nameCol.setMinWidth(200);
nameCol.setCellValueFactory(new PropertyValueFactory<>("i"));
// Allow to display Textflow in Column
nameCol.setCellFactory(column -> {
return new TableCell<MyData, Long>() {
@Override
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setStyle("");
} else {
// Generate Textflow with variable length
TextFlow textFlow = new TextFlow();
textFlow.setPrefHeight(Region.USE_COMPUTED_SIZE);
for (Long ii = 1L; ii <= item; ii++) {
Text text1 = new Text("la la la ");
text1.setFill(Color.RED);
Text text2 = new Text("blue blue blue ");
text2.setFill(Color.BLUE);
textFlow.getChildren().add(text1);
textFlow.getChildren().add(text2);
}
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(textFlow);
// setPrefHeight(20); // <- Shows the expected effect.
// However I want to have variable height of row.
setPrefHeight(Region.USE_COMPUTED_SIZE); // <- Why is that not working
}
}
};
});
table.setItems(data);
table.getColumns().addAll(nameCol);
((Group) scene.getRoot()).getChildren().addAll(table);
stage.setScene(scene);
stage.show();
}
public static class MyData {
private Long i;
public MyData(Long i) { this.i = i; }
public Long getI() { return i; }
}
}