我试图在TableView的单元格中显示富文本,并创建了自己的TableCell子类,并将TextFlow对象设置为图形。但是TextFlow具有这样的额外高度(TextFlow在右列中):
java - TableCell中的TextFlow具有额外的高度-LMLPHP
为什么会发生?

代码如下(我用Groovy编写了它,但是和Java几乎一样):

public class ContentCell extends TableCell<Word, WordContent> {

  protected void updateItem(WordContent wordContent, boolean isEmpty) {
    super.updateItem(wordContent, isEmpty)
    if (isEmpty || wordContent == null) {
      setText(null)
      setGraphic(null)
    } else {
      TextFlow textFlow = wordContent.getContentTextFlow()
      setText(null)
      setGraphic(textFlow)
    }
  }

}

public class DictionaryController implements Initializable {

  @FXML private TableView<Word> wordTableView
  @FXML private TableColumn<Word, String> nameColumn
  @FXML private TableColumn<Word, WordContent> contentColumn

  public void initialize(URL location, ResourceBundle resources) {
    contentColumn.setCellFactory() { TableColumn<Word, WordContent> column ->
      return new ContentCell()
    }
    for (int i : 0 ..< 50) {
      WordContent wordContent = new WordContent("test")
      Word word = new Word("test" + i.toString(), wordContent)
      wordTableView.getItems().add(word)
    }
  }

}

public class WordContent {

  private TextFlow contentTextFlow = new TextFlow()

  public WordContent(String content) {
    createContentTextFlow(content)
  }

  private void createContentTextFlow(String content) {
    Text contentText = new Text(content)
    contentTextFlow.getChildren().addAll(contentText)
  }

  public TextFlow getContentTextFlow() {
    return contentTextFlow
  }

}

public class Word {

  private StringProperty name = new SimpleStringProperty()
  private ObjectProperty<WordContent> content = new SimpleObjectProperty()

  public Word(String name, WordContent content) {
    this.name.set(name)
    this.content.set(content)
  }

  public StringProperty nameProperty() {
    return name
  }

  public ObjectProperty<WordContent> contentProperty() {
    return content
  }

}

最佳答案

我不知道为什么列高不能正确计算?但是,如果将TextFlow替换为FlowPane,则可以解决问题。

如果要换行,则必须替换此代码

private void createContentTextFlow(String content) {
Text contentText = new Text(content)
contentTextFlow.getChildren().addAll(contentText)
}


通过

private void createContentTextFlow(String content) {
Text contentText = new Text(content)
contentText.wrappingWidthProperty().bind(#your_column_object#.widthProperty().subtract(5))
contentTextFlow.getChildren().addAll(contentText)
}

10-08 02:22