我必须将样式文本转换为包装的简单文本(用于 SVG 自动换行)。我无法相信无法从JTextArea
. 所以我创建了一个小框架程序:
package bla;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextArea;
public class Example1 extends WindowAdapter {
private static String content = "01234567890123456789\n" + "0123456 0123456 01234567 01234567";
JTextArea text;
public Example1() {
Frame f = new Frame("TextArea Example");
f.setLayout(new BorderLayout());
Font font = new Font("Serif", Font.ITALIC, 20);
text = new JTextArea();
text.setFont(font);
text.setForeground(Color.blue);
text.setLineWrap(true);
text.setWrapStyleWord(true);
f.add(text, BorderLayout.CENTER);
text.setText(content);
// Listen for the user to click the frame's close box
f.addWindowListener(this);
f.setSize(100, 511);
f.show();
}
public static List<String> getLines( JTextArea text ) {
//WHAT SHOULD I WRITE HERE
return new ArrayList<String>();
}
public void windowClosing(WindowEvent evt) {
List<String> lines = getLines(text);
System.out.println( "Number of lines:" + lines.size());
for (String line : lines) {
System.out.println( line );
}
System.exit(0);
}
public static void main(String[] args) {
Example1 instance = new Example1();
}
}
如果你运行它,你会看到:
以及我期望的输出:
Number of lines:6
0123456789
0123456789
0123456
0123456
01234567
01234567
我应该写什么来代替评论?
完整答案:
因此,基于接受的答案的完整解决方案实际上不显示框架(请注意,您应该从结果中删除实际的换行符):
package bla;
import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.Utilities;
public class Example1 {
private static String content = "01234567890123456789\n" + "0123456 0123456 01234567 01234567";
public static List<String> getLines( String textContent, int width, Font font ) throws BadLocationException {
JTextArea text;
text = new JTextArea();
text.setFont(font);
text.setForeground(Color.blue);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setText(content);
text.setSize(width, 1);
int lastIndex = 0;
int index = Utilities.getRowEnd(text, 0);
List<String> result = new ArrayList<String>();
do {
result.add( textContent.substring( lastIndex, Math.min( index+1, textContent.length() ) ) );
lastIndex = index + 1;
}
while ( lastIndex < textContent.length() && ( index = Utilities.getRowEnd(text, lastIndex) ) > 0 );
return result;
}
public static void main(String[] args) throws BadLocationException {
Font font = new Font("Serif", Font.ITALIC, 20);
Example1 instance = new Example1();
for (String line : getLines(content,110,font)) {
System.out.println( line.replaceAll( "\n", "") );
}
}
}
我的开放性问题(不是那么重要),为什么包含 jtextarea 的 100px 宽度的框架比没有具有相同宽度的框架的 jtextarea 更晚地包装文本。对此有什么想法?