Enumerate the content elements with a ElementIterator in JTextArea in Java
Description
The following code shows how to enumerate the content elements with a ElementIterator in JTextArea.
Example
import java.awt.Font;
/*from ww w.j a va 2 s . c o m*/
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
public class Main extends JFrame {
public Main() {
JTextArea textarea = new JTextArea("Initial Text");
textarea.setFont(new Font("LucidaSans", Font.PLAIN, 40));
add(textarea);
Document doc = textarea.getDocument();
ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
Element e;
while ((e = it.next()) != null) {
if (e.isLeaf()) {
int rangeStart = e.getStartOffset();
int rangeEnd = e.getEndOffset();
String line = null;
try {
line = textarea.getText(rangeStart, rangeEnd - rangeStart);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(line);
}
}
}
public static void main(String[] args) {
JFrame frame = new Main();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »