gpt4 book ai didi

java - 计算给定设置宽度的 JTextArea 中的行数

转载 作者:行者123 更新时间:2023-11-30 07:16:24 26 4
gpt4 key购买 nike

我正在尝试可靠地计算给定宽度的 JTextArea 中的行数(包括来自换行和换行的行数)。我正在使用此信息来设置我的 GUI 中其他组件的高度(例如,对于 n 行,设置组件的 n*高度)。

我偶然发现了 this solution (转载如下)但是这个有问题。如果该行上没有太多文本,有时它会漏掉一行。例如,如果一个宽度为 100 的 JTextArea 有 3 行文本,而在第 3 行它只有宽度为 15 左右的文本,那么它将只计算 2 行而不是 3 行。

public class MyTextArea extends JTextArea {

//...

public int countLines(int width) {

AttributedString text = new AttributedString(this.getText());
FontRenderContext frc = this.getFontMetrics(this.getFont()).getFontRenderContext();
AttributedCharacterIterator charIt = text.getIterator();
LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIt, frc);
lineMeasurer.setPosition(charIt.getBeginIndex());

int noLines = 0;
while (lineMeasurer.getPosition() < charIt.getEndIndex()) {
lineMeasurer.nextLayout(width);
noLines++;
}

System.out.print("there are " + noLines + "lines" + System.getProperty("line.separator"));
return noLines;
}
}

知道是什么导致了这个问题吗?除了在 JTextArea 中计算行数之外,还有其他选择吗?谢谢。

最佳答案

I'm using this information to set the height of other components in my GUI.

相反,让每个组件采用其 preferred sizepack() 封闭容器。如图here , 您可以将文本区域添加到大小有限的滚动 Pane 中,可能是行高的方便倍数。更一般地说,您可以实现 Scrollable 接口(interface),如 here 所述。 .

关于java - 计算给定设置宽度的 JTextArea 中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17005336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com