📄 e973. retrieving the visible lines in a jtextcomponent.txt
字号:
There are hard and soft line breaks when viewing the contents of a text component. Hard line breaks are caused by a newline character in the contents. Soft line breaks are a result of word wrapping by the text component. Word wrapping occurs strictly on the display; it does not change the contents (i.e., newlines are not inserted into the contents).
This example demonstrates how to retrieve the contents with soft line breaks. The retrieval does not modify the contents; it returns the contents with additional newlines for soft line breaks.
Note: getWrappedLines() can be used directly if called within an event thread. To call it on a visible text component outside an event thread, use the Document.render() method to safely retrieve the text. See e971 Asynchronously Reading the Contents of a Visible JTextComponent for an example.
// Returns null if comp does not have a size
public static String getWrappedText(JTextComponent c) {
int len = c.getDocument().getLength();
int offset = 0;
// Increase 10% for extra newlines
StringBuffer buf = new StringBuffer((int)(len*1.10));
try {
while (offset < len) {
int end = Utilities.getRowEnd(c, offset);
if (end < 0) {
break;
}
// Include the last character on the line
end = Math.min(end+1, len);
String s = c.getDocument().getText(offset, end-offset);
buf.append(s);
// Add a newline if s does not have one
if (!s.endsWith("\n")) {
buf.append('\n');
}
offset = end;
}
} catch (BadLocationException e) {
}
return buf.toString();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -