【问题标题】:Add `\n` to JTextArea every wrap the word将 `\n` 添加到 JTextArea 每个换行单词
【发布时间】:2013-06-07 08:56:41
【问题描述】:

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

我希望每个 JTextArea 自动换行,然后添加一个新行 \ n ,因此在我的报告中具有相同的文本对齐。

请帮忙,谢谢:)

【问题讨论】:

  • 有自动换行和换行,Please help, thank you :) == 为了更好的帮助,尽快发布SSCCE,关于 JFrame 和 JTextArea,简短,可运行,可编译

标签: java swing jtextarea word-wrap


【解决方案1】:

您不应将“\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();
}

【讨论】:

  • +1 我没有 Java 环境来测试这个算法,但我猜(根据我对代码的理解)它可以工作(我不明白为什么它不会)。
  • @GuillaumePolet,感谢您的信任投票。我对使用自动换行的文本区域进行了有限的测试。
猜你喜欢
  • 1970-01-01
  • 2020-08-29
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
相关资源
最近更新 更多