How to extract the word and line wrapping information from JTextArea for text with given font
Posted
by
Gábor Lipták
on Stack Overflow
See other posts from Stack Overflow
or by Gábor Lipták
Published on 2012-06-01T23:27:40Z
Indexed on
2012/06/02
10:40 UTC
Read the original article
Hit count: 322
I have to convert styled text to wrapped simple text (for SVG word wrapping). I cannot beleive that the word wrapping information (how many lines are there, where are the line breaks) cannot be extracted from the JTextArea
. So I created a small frame program:
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();
}
}
If you run it you will see this:
And what I expect as output:
Number of lines:6
0123456789
0123456789
0123456
0123456
01234567
01234567
What should I write in place of the comment?
© Stack Overflow or respective owner