TableCell中的TextFlow具有额外的高度

时间:2016-05-29 03:17:39

标签: java javafx groovy

我尝试在TableView的单元格中显示富文本,然后创建了自己的TableCell子类并将TextFlow对象设置为图形。但TextFlow有一个额外的高度(TextFlow在右栏): TextFlow has an extra height 为什么会这样?

代码如下(我在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
  }

}

1 个答案:

答案 0 :(得分:1)

我不知道为什么列高度计算不正确?但是,如果您将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)
}