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

时间:2013-06-09 00:43:30

标签: java swing jtextarea multiline

我正在尝试可靠地计算给定设置宽度的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中有计数行的替代方法吗?感谢。

2 个答案:

答案 0 :(得分:2)

  

我正在使用此信息设置GUI中其他组件的高度。

相反,让每个组件采用其preferred sizepack()封闭容器。如图所示here,您可以将文本区域添加到大小有限的滚动窗格,也许是行高的方便倍数。更一般地说,您可以按照here概述实施Scrollable界面。

答案 1 :(得分:2)

所以我提出了一个简单的解决方案,它使用FontMetrics来计算文本的显示宽度,并通过将文本分成字符串标记,我可以计算出会有多少行。

public int countLines(int width) {

        FontMetrics fontMetrics = this.getFontMetrics(this.getFont());
        String text = this.getText();
        String[] tokens = text.split(" ");
        String currentLine = "";
        boolean beginningOfLine = true;
        int noLines = 1;

        for (int i = 0; i < tokens.length; i++) {
            if (beginningOfLine) {
                beginningOfLine = false;
                currentLine = currentLine + tokens[i];
            } else {
                currentLine = currentLine + " " + tokens[i];
            }

            if (fontMetrics.stringWidth(currentLine) > width) {
                currentLine = "";
                beginningOfLine = true;
                noLines++;
            }
        }

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