每次包装单词时,将“\ n”添加到JTextArea

时间:2013-06-07 08:56:42

标签: java swing jtextarea textwrapping

你好我有一个JTextArea和我txtResult.setWrapStyleWord program (true);,我还有一个从JTextArea获取数据的报告。

我想要每个自动JTextArea包装,然后添加一个新行\ n,所以在我的报告中有相同的文本对齐。

请帮助,谢谢:)

1 个答案:

答案 0 :(得分:2)

你不应该插入" \ n"进入文本区域。相反,当您想要保存文本时,应该创建一个辅助方法来执行此操作。代码类似于:

public String formatText(JTextArea textArea)
{
    StringBuilder text = new StringBuilder( textArea.getText() );
    int lineHeight = textArea.getFontMetrics( textArea.getFont() ).getHeight();
    Point view = new Point(textArea.getWidth(), textArea.getInsets().top);
    int length = textArea.getDocument().getLength();
    int endOfLine = textArea.viewToModel(view);
    int lines = 0;

    while (endOfLine < length)
    {
        int adjustedEndOfLine = endOfLine + lines;

        if (text.charAt(adjustedEndOfLine) == ' ')
        {
            text.insert(adjustedEndOfLine + 1, '\n');
            lines++;
        }

        view.y += lineHeight;
        endOfLine = textArea.viewToModel(view);
    }

    return text.toString();
}