如何将JTextArea中的换行文本转换为多个行分隔的字符串 [英] How to get line-wrapped text from JTextArea into multiple line-seperated Strings

查看:160
本文介绍了如何将JTextArea中的换行文本转换为多个行分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下属性的JTextArea:

I have a JTextArea with the following properties:

textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);

在GUI中,文本通常会自动换行,但是当我调用textArea.getText();时,将返回单行文本,没有任何行分隔符.

In the GUI the text is wrapped normally but when I call textArea.getText(); a single line of text is returned with no line separators.

我的问题是我如何才能将文本区域组件中的文本(如在GUI中一样)转换为String或字符串数​​组?

My question is how can I get the text from the text area component 'as it is in the GUI' into a String or an array of strings?

图片示例:

推荐答案

您可以通过textArea.size.width获得JTextArea的宽度,然后通过textArea.getGraphics().getFontMetrics(textArea.getFont())获得JTextArea的字体度量,使用FontMetrics可以计算特定字符串的宽度- fontMetrics.stringWidth("Some string here").

You can get width of JTextArea via textArea.size.width, then get font metrics of JTextArea via textArea.getGraphics().getFontMetrics(textArea.getFont()), using FontMetrics you can calculate width of a particular string - fontMetrics.stringWidth("Some string here").

然后,例如,您可以一个接一个地添加文本符号,直到超过JTextArea的宽度-然后再添加新行.

Then you can, for example, add symbols of text one by one until you surpass width of JTextArea - and start a new line when you do.

final String fullText = textArea.getText();
final int width = textArea.size.width;
final ArrayList lines = new ArrayList();
final FontMetrics fontMetrics = textArea.getGraphics().getFontMetrics(textArea.getFont());

StringBuilder sb = new StringBuilder(); 
for(final Character c : fullText) {
    sb.append(c);
    if(fontMetrics.stringWidth(sb.toString()) > width) { 
        sb.setLength(sb.length() - 1); 
        lines.add(sb.toString()); 
        sb = new StringBuilder(c.toString()); 
    }
}
lines.add(sb.toString()); 

这篇关于如何将JTextArea中的换行文本转换为多个行分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆