📄 e969. retrieving all the text from a jtextcomponent efficiently.txt
字号:
The text contained in a text component is not always stored contiguously. Therefore, retrieving text using getText() may cause a new String object to be created and the text copied to the new string. If you do not need the text in one contiguous chunk, the most efficient way to retrieve the text is in pieces called segments. This example retrieves the entire contents of a text component in segments.
// Create the text component
JTextComponent textComp = new JTextPane();
Document doc = textComp.getDocument();
// Create a segment to hold the characters in the document
Segment segment = new Segment();
int pos = 0;
segment.setPartialReturn(true);
try {
// Retrieve all segments
while (pos < doc.getLength()) {
// Ask for the remainder of the document text
doc.getText(pos, doc.getLength()-pos, segment);
// You can access the contents directly from the array in the segment.
// Never modify the contents of the array
for (int i=0; i<segment.count; i++) {
int positionInDoc = pos+i;
char charAtPos = segment.array[i+segment.offset];
}
// Or use the segment as a character iterator
int i=0;
for(char c=segment.first(); c != CharacterIterator.DONE; c=segment.next(), i++) {
int positionInDoc = pos+i;
char charAtPos = c;
}
// Increment pos by the actual number of characters retrieved
pos += segment.count;
}
} catch (BadLocationException e) {
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -