【发布时间】:2021-09-10 12:39:07
【问题描述】:
给定一个StyledText,用SWT.MULTI 和SWT.WRAP 初始化,我需要根据内容的适当行数计算适当的高度提示。
在这张图片中,您可以看到编辑器在内容更改时如何调整大小
计算要显示的行的代码如下
private int calcRealLinesCount() {
final int componentWidth = styledText.getSize().x;
final int dumbLinesCount = styledText.getLineCount();
int realLinesCount = 0;
for (int i = 0; i < dumbLinesCount; i++) {
final String lineText = styledText.getLine(i);
final Point lineTextExtent = styledTextGc.textExtent(lineText);
final double lines = lineTextExtent.x / (double) componentWidth;
realLinesCount += (int) Math.max(1D, Math.ceil(lines));
}
return Math.max(dumbLinesCount, realLinesCount);
}
然后使用行数来获得适当的高度
((GridData) layoutData).heightHint = realLinesCount * fontHeight;
但是,此代码不考虑自动换行,我想不出办法。
有任何想法吗?我可以换一种方式吗?
【问题讨论】:
-
为什么需要高度?我想说让 StyledText 填充所有可用空间或只是固定大小更常见。
org.eclipse.jface.text.JFaceTextUtil有一个computeLineHeight声称可以处理 wrap。 -
@greg-449 不幸的是,我需要保持这种行为,否则我也会将其保持在固定大小。我会试试 computeLineHeight 并报告。谢谢!
-
@greg-449 非常感谢!你可以在我的回答中看到我的结果。
标签: java swt styledtext