📄 e984. enumerating the lines in a jtextarea component.txt
字号:
The contents of a text component are stored in a Document object that, in turn, breaks the content into a hierarchy of Element objects. In the case of a text area, each line of text (a contiguous span of characters terminated by a single newline) is stored in a content element. For example, if the last line of the contents is terminated by a newline and there are 100 new lines, there will be 100 content elements. All content elements are stored under a single paragraph element.
This example demonstrates how to retrieve the paragraph element and enumerate all children content elements.
See also e973 Retrieving the Visible Lines in a JTextComponent.
// Create a text area
JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
// Get paragraph element
Element paragraph = textArea.getDocument().getDefaultRootElement();
// Get number of content elements
int contentCount = paragraph.getElementCount();
// Get index ranges for each content element.
// Each content element represents one line.
// Each line includes the terminating newline.
for (int i=0; i<contentCount; i++) {
Element e = paragraph.getElement(i);
int rangeStart = e.getStartOffset();
int rangeEnd = e.getEndOffset();
try {
String line = textArea.getText(rangeStart, rangeEnd-rangeStart);
} catch (BadLocationException ex) {
}
}
Here is another way to enumerate the content elements with a ElementIterator:
// Get the text area's document
Document doc = textArea.getDocument();
// Create an iterator using the root element
ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
// Iterate all content elements (which are leaves)
Element e;
while ((e=it.next()) != null) {
if (e.isLeaf()) {
int rangeStart = e.getStartOffset();
int rangeEnd = e.getEndOffset();
try {
String line = textArea.getText(rangeStart, rangeEnd-rangeStart);
} catch (BadLocationException ex) {
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -