下面列出了javax.swing.text.Element#getElement ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Reparses the document, by passing the specified lines to the token marker. This should be
* called after a large quantity of text is first inserted.
*
* @param start
* The first line to parse
* @param len
* The number of lines, after the first one to parse
*/
public void tokenizeLines(int start, int len) {
if (tokenMarker == null || !tokenMarker.supportsMultilineTokens()) {
return;
}
Segment lineSegment = new Segment();
Element map = getDefaultRootElement();
len += start;
try {
for (int i = start; i < len; i++) {
Element lineElement = map.getElement(i);
int lineStart = lineElement.getStartOffset();
getText(lineStart, lineElement.getEndOffset() - lineStart - 1, lineSegment);
tokenMarker.markTokens(lineSegment, i);
}
} catch (BadLocationException bl) {
bl.printStackTrace();
}
}
private static void removeTrailingWhitespace(Document doc) throws Exception {
Element lineRoot = DocumentUtilities.getParagraphRootElement(doc);
CharSequence docText = DocumentUtilities.getText(doc);
int lineCount = lineRoot.getElementCount();
for (int i = 0; i < lineCount; i++) {
Element lineElem = lineRoot.getElement(i);
int lineStartOffset = lineElem.getStartOffset();
int lineLastOffset = lineElem.getEndOffset() - 1;
int offset;
for (offset = lineLastOffset - 1; offset >= lineStartOffset; offset--) {
char c = docText.charAt(offset);
// Currently only remove ' ' and '\t' - may be revised
if (c != ' ' && c != '\t') {
break;
}
}
// Increase offset (either below lineStartOffset or on non-white char)
offset++;
if (offset < lineLastOffset) {
doc.remove(offset, lineLastOffset - offset);
}
}
}
public static void checkNoTrailingWhitespace(Document doc) {
Element lineRoot = DocumentUtilities.getParagraphRootElement(doc);
CharSequence docText = DocumentUtilities.getText(doc);
for (int i = 0; i < lineRoot.getElementCount(); i++) {
Element lineElem = lineRoot.getElement(i);
int lineLastOffset = lineElem.getEndOffset() - 2;
if (lineLastOffset >= lineElem.getStartOffset()) { // At least one non newline char
switch (docText.charAt(lineLastOffset)) {
case ' ':
case '\t':
throw new IllegalStateException("Trailing whitespace exists at lineIndex=" + i + // NOI18N
", lineStartOffset=" + lineElem.getStartOffset() + // NOI18N
", lineEndOffset=" + lineElem.getEndOffset() + // NOI18N
'\n' + dumpLines(null, doc));
}
}
}
}
/**
* Returns the offset where the selection ends on the specified line.
*/
public int getSelectionEnd(int line) {
if (line == selectionEndLine) {
return selectionEnd;
} else if (rectSelect) {
Element map = document.getDefaultRootElement();
int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();
Element lineElement = map.getElement(line);
int lineStart = lineElement.getStartOffset();
int lineEnd = lineElement.getEndOffset() - 1;
return Math.min(lineEnd, lineStart + end);
} else {
return getLineEndOffset(line) - 1;
}
}
public static String getAllText(Element e){
try {
StringBuffer sb = new StringBuffer();
int count = e.getElementCount();
for (int i = 0; i < count; i++) {
Element c = e.getElement(i);
AttributeSet abC = c.getAttributes();
if (abC.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT)
sb.append(getText(c));
}
return sb.toString();
} catch (Exception er) {
er.printStackTrace();
}
return null;
}
/**
* Get string representation of an offset for debugging purposes
* in form "offset[line:column]". Both lines and columns start counting from 1
* like in the editor's status bar. Tabs are expanded when counting the column.
*
* @param sb valid string builder to which text will be appended or null in which case
* the method itself will create a string builder and it will return it.
* @param doc non-null document in which the offset is located.
* @param offset offset in the document.
* @return non-null string builder to which the description was added.
* @since 1.27
*/
public static StringBuilder appendOffset(StringBuilder sb, Document doc, int offset) {
if (sb == null) {
sb = new StringBuilder(50);
}
sb.append(offset).append('[');
if (offset < 0) { // Offset too low
sb.append("<0");
} else if (offset > doc.getLength() + 1) { // +1 for AbstractDocument-based docs
sb.append(">").append(doc.getLength());
} else { // Valid offset
Element paragraphRoot = getParagraphRootElement(doc);
int lineIndex = paragraphRoot.getElementIndex(offset);
Element lineElem = paragraphRoot.getElement(lineIndex);
sb.append(lineIndex + 1).append(':'); // Line
sb.append(visualColumn(doc, lineElem.getStartOffset(), offset) + 1); // Column
}
sb.append(']');
return sb;
}
protected String getTextLineNumber(int rowStartOffset)
{
Element root = component.getDocument().getDefaultRootElement();
int index = root.getElementIndex( rowStartOffset );
Element line = root.getElement( index );
if (line.getStartOffset() == rowStartOffset)
return String.valueOf(index + 1);
else
return "";
}
/**
* Returns a TreePath to the element at <code>position</code>.
*/
protected TreePath getPathForIndex(int position, Object root,
Element rootElement) {
TreePath path = new TreePath(root);
Element child = rootElement.getElement(rootElement.getElementIndex(
position));
path = path.pathByAddingChild(rootElement);
path = path.pathByAddingChild(child);
while (!child.isLeaf()) {
child = child.getElement(child.getElementIndex(position));
path = path.pathByAddingChild(child);
}
return path;
}
/**
* Returns a TreePath to the element at <code>position</code>.
*/
protected TreePath getPathForIndex(int position, Object root,
Element rootElement) {
TreePath path = new TreePath(root);
Element child = rootElement.getElement(rootElement.getElementIndex(
position));
path = path.pathByAddingChild(rootElement);
path = path.pathByAddingChild(child);
while (!child.isLeaf()) {
child = child.getElement(child.getElementIndex(position));
path = path.pathByAddingChild(child);
}
return path;
}
private void removeFromStart(Document document, Element root) {
Element line = root.getElement(0);
int end = line.getEndOffset();
try {
document.remove(0, end);
} catch (BadLocationException ble) {
System.out.println(ble);
}
}
/**
* Returns a TreePath to the element at <code>position</code>.
*/
protected TreePath getPathForIndex(int position, Object root,
Element rootElement) {
TreePath path = new TreePath(root);
Element child = rootElement.getElement(rootElement.getElementIndex(
position));
path = path.pathByAddingChild(rootElement);
path = path.pathByAddingChild(child);
while (!child.isLeaf()) {
child = child.getElement(child.getElementIndex(position));
path = path.pathByAddingChild(child);
}
return path;
}
/**
*
*/
protected void addElements(List<Element> elements, Element element)
{
if(element instanceof LeafElement)
{
elements.add(element);
}
for(int i = 0; i < element.getElementCount(); i++)
{
Element child = element.getElement(i);
addElements(elements, child);
}
}
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return null;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
final Element line = root.getElement(lineIndex);
if (line == null) return null;
return new int[] { line.getStartOffset(), line.getEndOffset() };
}
private static void removeLines(Document doc, Element root) {
Element fl = root.getElement(0);
try {
doc.remove(0, fl.getEndOffset());
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
}
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return null;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
final Element line = root.getElement(lineIndex);
if (line == null) return null;
return new int[] { line.getStartOffset(), line.getEndOffset() };
}
protected void traverseElementById(Element element) {
if (element.isLeaf()) {
checkId(element);
} else {
for (int i = 0; i < element.getElementCount(); i++) {
Element child = element.getElement(i);
checkId(child);
if (!child.isLeaf()) {
traverseElementById(child);
}
}
}
}
static void invalidateAllSyntaxStateInfos(BaseDocument doc) {
Element lineRoot = getLineRoot(doc);
int elemCount = lineRoot.getElementCount();
for (int i = elemCount - 1; i >= 0; i--) {
LineElement line = (LineElement) lineRoot.getElement(i);
line.legacySetAttributesObject(null);
}
}
protected @Override View createCustomView(ViewFactory f,
int startOffset, int maxEndOffset, int elementIndex) {
if (elementIndex == -1) {
throw new IllegalStateException("Need underlying line element structure"); // NOI18N
}
View view = null;
Element elem = getElement();
Element lineElem = elem.getElement(elementIndex);
view = f.create(lineElem);
return view;
}
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return null;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
final Element line = root.getElement(lineIndex);
if (line == null) return null;
return new int[] { line.getStartOffset(), line.getEndOffset() };
}
static String forPane(JEditorPane p) {
if (p == null) return null;
String selection = p.getSelectedText ();
if ( selection != null && selection.length() > 0 ) {
return selection;
} else {
// try to guess which word is underneath the caret's dot.
Document doc = p.getDocument();
Element lineRoot;
if (doc instanceof StyledDocument) {
lineRoot = NbDocument.findLineRootElement((StyledDocument)doc);
} else {
lineRoot = doc.getDefaultRootElement();
}
int dot = p.getCaret().getDot();
Element line = lineRoot.getElement(lineRoot.getElementIndex(dot));
if (line == null) return null;
String text = null;
try {
text = doc.getText(line.getStartOffset(),
line.getEndOffset() - line.getStartOffset());
} catch (BadLocationException e) {
return null;
}
if ( text == null )
return null;
int pos = dot - line.getStartOffset();
if ( pos < 0 || pos >= text.length() )
return null;
int bix, eix;
for( bix = Character.isJavaIdentifierPart( text.charAt( pos ) ) ? pos : pos - 1;
bix >= 0 && Character.isJavaIdentifierPart( text.charAt( bix ) ); bix-- );
for( eix = pos; eix < text.length() && Character.isJavaIdentifierPart( text.charAt( eix )); eix++ );
return bix == eix ? null : text.substring( bix + 1, eix );
}
}