如果TextArea通过设置setWrapText(true)
包装文本,如何确定行数?行数我指的是用户在整个TextArea包含可滚动内容中可视化的行数。
将\n
分割文本或询问段落计数都不起作用,因为包装与实际的行拆分无关。
答案 0 :(得分:0)
这是我迄今为止的解决方案,核心原则围绕这样一个事实,即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;
}
希望这有帮助!