【问题标题】:Determine number of lines if TextArea which wraps the text如果 TextArea 包含文本,则确定行数
【发布时间】:2018-02-05 16:49:30
【问题描述】:

如果 TextArea 通过设置 setWrapText(true) 来换行文本,如何确定行数?行数是指用户在整个 TextArea 可滚动内容中可视化的行数。

\n 分割文本和询问段落计数都不起作用,因为换行与实际的行分割无关。

【问题讨论】:

标签: user-interface javafx


【解决方案1】:

到目前为止,这是我的解决方案,核心原则围绕着这样一个事实,即 javafx 中 FontMetrics 类返回的行高(略微)偏离了由 Text 节点确定的实际行高,这导致在使用这种类型的节点作为助手的基本思想。

计算带有活动换行文本的行数

基本上通过使用帮助器Text 节点进行测量、重置和恢复该帮助器上的环绕宽度并记录高度变化来确定实际行高。

计算没有有效换行文本的行数

这是最简单的:在这种情况下,paragraphs 属性的大小直接对应于行数:

将它们放在一起可能看起来像这样:

  /**
   * Calculates the current amount of rows in the textarea regardless 
   * of "wordWrap" set to {@code true} or {@code false}.
   * 
   * @return the current count of rows; {@code 0} if the count could not be determined
   */
  private int getRowCount() {
    int currentRowCount = 0;
    Text helper = new Text();
    /*
     * Little performance improvement: If "wrapText" is set to false, then the
     * list of paragraphs directly corresponds to the line count, otherwise we need 
     * to get creative...
     */
    if(this.textArea.isWrapText()) {
      // text needs to be on the scene
      Text text = (Text) textArea.lookup(".text");
      if(text == null) {
        return currentRowCount;
      }
      /*
       * Now we just count the paragraphs: If the paragraph size is less
       * than the current wrappingWidth then increment; Otherwise use our
       * Text helper instance to calculate the change in height for the 
       * current paragraph with "wrappingWidth" set to the actual 
       * wrappingWidth of the TextArea text
       */
      helper.setFont(textArea.getFont());
      for (CharSequence paragraph : textArea.getParagraphs()) {
        helper.setText(paragraph.toString());
        Bounds localBounds = helper.getBoundsInLocal();

        double paragraphWidth = localBounds.getWidth();
        if(paragraphWidth > text.getWrappingWidth()) {          
          double oldHeight = localBounds.getHeight();
          // this actually sets the automatic size adjustment into motion...
          helper.setWrappingWidth(text.getWrappingWidth());
          double newHeight = helper.getBoundsInLocal().getHeight();
          // ...and we reset it after computation
          helper.setWrappingWidth(0.0D);

          int paragraphLineCount = Double.valueOf(newHeight / oldHeight).intValue();
          currentRowCount += paragraphLineCount;
        } else {
          currentRowCount += 1;
        }
      }
    } else {
      currentRowCount = textArea.getParagraphs().size();
    }
    return currentRowCount;
  }

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 2017-11-29
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多