javax.swing.text.JTextComponent#getDocument ( )源码实例Demo

下面列出了javax.swing.text.JTextComponent#getDocument ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netbeans   文件: WordMatch.java
private Document getNextDocument() {
    // Initially documentIndex == -1
    if (documentIndex == documents.size() - 1) { // Check adding
        if (documentSet.isEmpty()) { // documents list not inited yet -> add 'doc'
            documentSet.put(doc, Boolean.TRUE);
        }
        for (JTextComponent tc : EditorRegistry.componentList()) {
            Document d = tc.getDocument();
            if (!documentSet.containsKey(d)) {
                documentSet.put(d, Boolean.TRUE);
                documents.add(new WeakReference<Document>(d));
            }
        }
    }
    Document retDoc = null;
    while (documentIndex < documents.size() - 1) {
        documentIndex++;
        retDoc = documents.get(documentIndex).get();
        if (retDoc != null) {
            break;
        }
    }
    return retDoc;
}
 
源代码2 项目: netbeans   文件: CamelCaseOperations.java
static int nextCamelCasePosition(JTextComponent textComponent) {
    int offset = textComponent.getCaretPosition();
    Document doc = textComponent.getDocument();

    // Are we at the end of the document?
    if (offset == doc.getLength()) {
        return -1;
    }

    KeystrokeHandler bc = UiUtils.getBracketCompletion(doc, offset);
    if (bc != null) {
        int nextOffset = bc.getNextWordOffset(doc, offset, false);
        if (nextOffset != -1) {
            return nextOffset;
        }
    }
    
    try {
        return Utilities.getNextWord(textComponent, offset);
    } catch (BadLocationException ble) {
        // something went wrong :(
        ErrorManager.getDefault().notify(ble);
    }
    return -1;
}
 
源代码3 项目: java-swing-tips   文件: MainPanel.java
private static void setHighlight(JTextComponent jtc, String pattern) {
  Highlighter highlighter = jtc.getHighlighter();
  highlighter.removeAllHighlights();
  try {
    Document doc = jtc.getDocument();
    String text = doc.getText(0, doc.getLength());
    Matcher matcher = Pattern.compile(pattern).matcher(text);
    int pos = 0;
    while (matcher.find(pos) && !matcher.group().isEmpty()) {
      pos = matcher.end();
      highlighter.addHighlight(matcher.start(), pos, HIGHLIGHT);
    }
    // while ((pos = text.indexOf(pattern, pos)) >= 0) {
    //   highlighter.addHighlight(pos, pos + pattern.length(), HIGHLIGHT);
    //   pos += pattern.length();
    // }
  } catch (BadLocationException | PatternSyntaxException ex) {
    UIManager.getLookAndFeel().provideErrorFeedback(jtc);
  }
}
 
源代码4 项目: visualvm   文件: ActionUtils.java
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * 
 * Note that the strings returned will not contain the terminating line feeds
 * 
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument pDoc = (PlainDocument) target.getDocument();
        int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // if more than one line is selected, we need to subtract one from the end
            // so that we do not select the line with the caret and no selection in it
            end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = pDoc.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException ex) {
        Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        lines = EMPTY_STRING_ARRAY;
    }
    return lines;
}
 
源代码5 项目: netbeans   文件: JspCompletionItem.java
@Override
public void defaultAction(JTextComponent component) {
    super.defaultAction(component);
    final BaseDocument doc = (BaseDocument) component.getDocument();

    doc.runAtomic(new Runnable() {

        @Override
        public void run() {
            try {
                doc.insertString(Util.findPositionForJspDirective(doc),
                        "<%@ taglib prefix=\"" //NOI18N
                        + tagLibPrefix + "\" uri=\"" //NOI18N
                        + tagLibURI + "\" %>\n", null);     //NOI18N

            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
}
 
源代码6 项目: netbeans   文件: ToggleBlockCommentAction.java
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    final AtomicBoolean processedHere = new AtomicBoolean(false);
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled() || !(target.getDocument() instanceof BaseDocument)) {
            target.getToolkit().beep();
            return;
        }
        final Positions positions = Positions.create(target);
        final BaseDocument doc = (BaseDocument) target.getDocument();
        doc.runAtomic(new Runnable() {

            @Override
            public void run() {
                performCustomAction(doc, positions, processedHere);
            }
        });
        if (!processedHere.get()) {
            performDefaultAction(evt, target);
        }
    }
}
 
源代码7 项目: rapidminer-studio   文件: TextActions.java
@Override
public void actionPerformed(ActionEvent e) {
	JTextComponent target = getTextComponent(e);
	boolean beep = true;
	if ((target != null) && (target.isEditable())) {
		try {
			Document doc = target.getDocument();
			int ss = 0;
			int se = doc.getLength();

			if (ss != se) {
				doc.remove(ss, se - ss);
				beep = false;
			}
		} catch (BadLocationException bl) {
		}
	}
	if (beep) {
		UIManager.getLookAndFeel().provideErrorFeedback(target);
	}
}
 
源代码8 项目: netbeans   文件: CompletionSupport.java
public void processKeyEvent (KeyEvent evt) {
    if (evt.getID() == KeyEvent.KEY_TYPED) {
        char c = evt.getKeyChar();
        JTextComponent component = (JTextComponent)evt.getSource();
        if (confirmChars == null) {
            confirmChars = getConfirmChars(component);
        }
        if (confirmChars.indexOf(c) != -1) {
            if (c != '.') {
                Completion.get().hideDocumentation();
                Completion.get().hideCompletion();
            }
            NbEditorDocument doc = (NbEditorDocument) component.getDocument ();
            try {
                defaultAction(component);
                doc.insertString(processKeyEventOffset, Character.toString(c), null);
            } catch (BadLocationException e) {
            }
            if (c == '.')
                Completion.get().showCompletion();
            evt.consume();
        } // if
    } // if
}
 
源代码9 项目: jpexs-decompiler   文件: ActionUtils.java
/**
 * If the selection is multi lined, then the full lines are selected,
 * otherwise, nothing is done.
 * @param target
 * @return true if the selection is multi-line, or a whole line
 */
public static boolean selectLines(JTextComponent target) {
	if (target.getSelectionStart() == target.getSelectionEnd()) {
		return false;
	}
	PlainDocument pDoc = (PlainDocument) target.getDocument();
	Element es = pDoc.getParagraphElement(target.getSelectionStart());
	// if more than one line is selected, we need to subtract one from the end
	// so that we do not select the line with the caret and no selection in it
	Element ee = pDoc.getParagraphElement(target.getSelectionEnd() - 1);
	if (es.equals(ee) && ee.getEndOffset() != target.getSelectionEnd()) {
		return false;
	}
	int start = es.getStartOffset();
	int end = ee.getEndOffset();
	target.select(start, end - 1);
	return true;
}
 
源代码10 项目: netbeans   文件: HtmlCompletionProvider.java
@Override
protected boolean canFilter(JTextComponent component) {
    try {
        if (component.getCaret() == null || component.getCaretPosition() < anchor) {
            return false;
        }
        
        Document doc = component.getDocument();
        int offset = component.getCaretPosition();

        String prefix = doc.getText(anchor, offset - anchor);

        //check the items
        for (CompletionItem item : items) {
            if (item instanceof HtmlCompletionItem) {
                String itemText = ((HtmlCompletionItem) item).getItemText();
                if(itemText != null) { //http://netbeans.org/bugzilla/show_bug.cgi?id=222234
                    if (startsWithIgnoreCase(itemText, prefix)) {
                        return true; //at least one item will remain
                    }
                } else {
                    LOG.log(Level.WARNING, "CompletionItem {0} returned null from getItemText()!", item);
                }
            }
        }


    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return false;

}
 
源代码11 项目: netbeans   文件: CaretBasedBlockHighlighting.java
/** Creates a new instance of CaretSelectionLayer */
protected CaretBasedBlockHighlighting(JTextComponent component, String coloringName, boolean extendsEOL, boolean extendsEmptyLine) {
    // Determine the mime type
    String mimeType = BlockHighlighting.getMimeType(component);
    this.mimePath = mimeType == null ? MimePath.EMPTY : MimePath.parse(mimeType);

    this.coloringName = coloringName;
    this.extendsEOL = extendsEOL;
    this.extendsEmptyLine = extendsEmptyLine;
    
    // Hook up the component
    this.component = component;
    
    selectionsBag = new PositionsBag(component.getDocument(), false);
}
 
源代码12 项目: visualvm   文件: ActionUtils.java
/**
 * Gets the Line Number at the give position of the editor component.
 * The first line number is ZERO
 * @param editor
 * @param pos
 * @return line number
 * @throws javax.swing.text.BadLocationException
 */
public static int getLineNumber(JTextComponent editor, int pos)
        throws BadLocationException {
    if (getSyntaxDocument(editor) != null) {
        SyntaxDocument sdoc = getSyntaxDocument(editor);
        return sdoc.getLineNumberAt(pos);
    } else {
        Document doc = editor.getDocument();
        return doc.getDefaultRootElement().getElementIndex(pos);
    }
}
 
源代码13 项目: jdk8u60   文件: ElementTreePanel.java
/**
 * Resets the JTextComponent to <code>editor</code>. This will update
 * the tree accordingly.
 */
public void setEditor(JTextComponent editor) {
    if (this.editor == editor) {
        return;
    }

    if (this.editor != null) {
        Document oldDoc = this.editor.getDocument();

        oldDoc.removeDocumentListener(this);
        this.editor.removePropertyChangeListener(this);
        this.editor.removeCaretListener(this);
    }
    this.editor = editor;
    if (editor == null) {
        treeModel = null;
        tree.setModel(null);
    } else {
        Document newDoc = editor.getDocument();

        newDoc.addDocumentListener(this);
        editor.addPropertyChangeListener(this);
        editor.addCaretListener(this);
        treeModel = new ElementTreeModel(newDoc);
        tree.setModel(treeModel);
    }
}
 
源代码14 项目: netbeans   文件: Utilities.java
/** Get the identifier around the given position or null if there's no identifier
 * around the given position. The identifier is not verified against SyntaxSupport.isIdentifier().
 * @param c JTextComponent to work on
 * @param offset position in document - usually the caret.getDot()
 * @return the block (starting and ending position) enclosing the identifier
 * or null if no identifier was found
 */
public static int[] getIdentifierBlock(JTextComponent c, int offset)
throws BadLocationException {
    CharSequence id = null;
    int[] ret = null;
    Document doc = c.getDocument();
    int idStart = javax.swing.text.Utilities.getWordStart(c, offset);
    if (idStart >= 0) {
        int idEnd = javax.swing.text.Utilities.getWordEnd(c, idStart);
        if (idEnd >= 0) {
            id = DocumentUtilities.getText(doc, idStart, idEnd - idStart);
            ret = new int[] { idStart, idEnd };
            CharSequence trim = CharSequenceUtilities.trim(id);
            if (trim.length() == 0 || (trim.length() == 1 && !Character.isJavaIdentifierPart(trim.charAt(0)))) {
                int prevWordStart = javax.swing.text.Utilities.getPreviousWord(c, offset);
                if (offset == javax.swing.text.Utilities.getWordEnd(c,prevWordStart )){
                    ret = new int[] { prevWordStart, offset };
                } else {
                    return null;
                }
            } else if ((id != null) && (id.length() != 0)  && (CharSequenceUtilities.indexOf(id, '.') != -1)){ //NOI18N
                int index = offset - idStart;
                int begin = CharSequenceUtilities.lastIndexOf(id.subSequence(0, index), '.');
                begin = (begin == -1) ? 0 : begin + 1; //first index after the dot, if exists
                int end = CharSequenceUtilities.indexOf(id, '.', index);
                end = (end == -1) ? id.length() : end;
                ret = new int[] { idStart+begin, idStart+end };
            }
        }
    }
    return ret;
}
 
源代码15 项目: netbeans   文件: Install.java
public synchronized void propertyChange(PropertyChangeEvent evt) {
    JTextComponent jtc = EditorRegistry.focusedComponent();
    if (jtc == null) return;
    
    Document active = jtc.getDocument();
    Object sourceProperty = active.getProperty(Document.StreamDescriptionProperty);
    if (!(sourceProperty instanceof DataObject)) return;

    FileObject activeFile = ((DataObject)sourceProperty).getPrimaryFile();
    TimesCollectorPeer.getDefault().select(activeFile);
}
 
源代码16 项目: netbeans   文件: BaseCaret.java
/**
 * Extend rectangular selection either by char in a specified selection
 * or by word (if ctrl is pressed).
 *
 * @param toRight true for right or false for left.
 * @param ctrl 
 */
public void extendRectangularSelection(boolean toRight, boolean ctrl) {
    JTextComponent c = component;
    Document doc = c.getDocument();
    int dotOffset = getDot();
    Element lineRoot = doc.getDefaultRootElement();
    int lineIndex = lineRoot.getElementIndex(dotOffset);
    Element lineElement = lineRoot.getElement(lineIndex);
    float charWidth;
    LockedViewHierarchy lvh = ViewHierarchy.get(c).lock();
    try {
        charWidth = lvh.getDefaultCharWidth();
    } finally {
        lvh.unlock();
    }
    int newDotOffset = -1;
    try {
        int newlineOffset = lineElement.getEndOffset() - 1;
        Rectangle newlineRect = c.modelToView(newlineOffset);
        if (!ctrl) {
            if (toRight) {
                if (rsDotRect.x < newlineRect.x) {
                    newDotOffset = dotOffset + 1;
                } else {
                    rsDotRect.x += charWidth;
                }
            } else { // toLeft
                if (rsDotRect.x > newlineRect.x) {
                    rsDotRect.x -= charWidth;
                    if (rsDotRect.x < newlineRect.x) { // Fix on rsDotRect
                        newDotOffset = newlineOffset;
                    }
                } else {
                    newDotOffset = Math.max(dotOffset - 1, lineElement.getStartOffset());
                }
            }

        } else { // With Ctrl
            int numVirtualChars = 8; // Number of virtual characters per one Ctrl+Shift+Arrow press
            if (toRight) {
                if (rsDotRect.x < newlineRect.x) {
                    newDotOffset = Math.min(Utilities.getNextWord(c, dotOffset), lineElement.getEndOffset() - 1);
                } else { // Extend virtually
                    rsDotRect.x += numVirtualChars * charWidth;
                }
            } else { // toLeft
                if (rsDotRect.x > newlineRect.x) { // Virtually extended
                    rsDotRect.x -= numVirtualChars * charWidth;
                    if (rsDotRect.x < newlineRect.x) {
                        newDotOffset = newlineOffset;
                    }
                } else {
                    newDotOffset = Math.max(Utilities.getPreviousWord(c, dotOffset), lineElement.getStartOffset());
                }
            }
        }

        if (newDotOffset != -1) {
            rsDotRect = c.modelToView(newDotOffset);
            moveDot(newDotOffset); // updates rs and fires state change
        } else {
            updateRectangularSelectionPaintRect();
            fireStateChanged();
        }
    } catch (BadLocationException ex) {
        // Leave selection as is
    }
}
 
源代码17 项目: netbeans   文件: RestClientEditorDrop.java
private boolean doHandleTransfer(final JTextComponent targetComponent) {
    final Document targetDoc = targetComponent.getDocument();
    final FileObject targetSource = NbEditorUtilities.getFileObject(targetDoc);
    Project targetProject = FileOwnerQuery.getOwner(targetSource);
    Method m = method.getWadlMethod();
    if(m == null)
        Exceptions.printStackTrace(new IOException("Wadl method not found"));
    final String displayName = m.getName();
    
    targetFO = getTargetFile(targetDoc);

    if (targetFO == null) {
        return false;
    }

    final List<Exception> errors = new ArrayList<Exception>();
   
    final ProgressDialog dialog = new ProgressDialog(
            NbBundle.getMessage(RestClientEditorDrop.class, "LBL_CodeGenProgress", 
            displayName));

    generatorTask = RequestProcessor.getDefault().create(new Runnable() {
        public void run() {
            try {
                SaasClientCodeGenerator codegen = (SaasClientCodeGenerator) 
                        SaasClientCodeGenerationManager.lookup(method, targetDoc);
                codegen.init(method, targetDoc);
                codegen.setDropLocation(targetComponent);
            
                RestClientSaasBean bean = (RestClientSaasBean) codegen.getBean();
                List<ParameterInfo> allParams = bean.filterParametersByAuth(
                        bean.filterParameters(new ParamFilter[]{ParamFilter.FIXED}));
                boolean response = Util.showDialog(displayName, allParams, targetDoc);
                if(response)
                    Util.doGenerateCode(codegen, dialog, errors);
            } catch (Exception ioe) {
                if(Constants.UNSUPPORTED_DROP.equals(ioe.getMessage())) {
                    Util.showUnsupportedDropMessage(new Object[] {
                        targetSource.getNameExt(), "Java Client"});
                    return;
                }
                errors.add(ioe);
            } finally {
                dialog.close();
            }
        }
    });

    generatorTask.schedule(50);

    dialog.open();

    if (errors.size() > 0) {
        Exceptions.printStackTrace(errors.get(0));
        return false;
    }
    return true;
}
 
源代码18 项目: netbeans   文件: CompletionSupport.java
private String getConfirmChars (JTextComponent component) {
    NbEditorDocument doc = (NbEditorDocument) component.getDocument ();
    StringBuffer buf = new StringBuffer();
    int offset = component.getCaret ().getDot ();
    try {
        TokenHierarchy tokenHierarchy = TokenHierarchy.get (doc);
        if (doc instanceof NbEditorDocument) {
            ((NbEditorDocument) doc).readLock ();
        }
        try {
            TokenSequence sequence = tokenHierarchy.tokenSequence ();
            if (sequence.isEmpty()) {
                return ""; // NOI18N
            }
            
            //find most embedded token sequence on the specified offset
            while(true) {
                sequence.move (offset - 1);
                if (!sequence.moveNext()) {
                    return ""; // NOI18N
                }
                TokenSequence embedded = sequence.embedded ();
                if (embedded == null) break;
                sequence = embedded;
            }
            Token token = sequence.token ();
            String tokenType = token.id ().name ();
            String mimeType = sequence.language ().mimeType ();
            Language l = LanguagesManager.getDefault ().getLanguage (mimeType);
            List<Feature> features = l.getFeatureList ().getFeatures (CompletionProviderImpl.COMPLETION, tokenType);
            Iterator<Feature> it = features.iterator ();
            while (it.hasNext ()) {
                Feature feature =  it.next ();
                String confChars = (String) feature.getValue("confirmChars"); // NOI18N
                if (confChars != null) {
                    buf.append(confChars);
                }
            }
        } finally {
            if (doc instanceof NbEditorDocument)
                ((NbEditorDocument) doc).readUnlock ();
        }
    } catch (LanguageDefinitionNotFoundException ex) {
    }
    return buf.toString();
}
 
源代码19 项目: netbeans   文件: ActionFactory.java
@Override
public void actionPerformed (final ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled()) {
            target.getToolkit().beep();
            return;
        }
        final BaseDocument doc = (BaseDocument) target.getDocument();
        if (doc instanceof GuardedDocument && ((GuardedDocument) doc).isPosGuarded(target.getCaretPosition())) {
            target.getToolkit().beep();
            return;
        }
        doc.runAtomicAsUser (new Runnable () {
            @Override
            public void run () {
                DocumentUtilities.setTypingModification(doc, true);
                try {
                    Element rootElement = doc.getDefaultRootElement();

                    Caret caret = target.getCaret();
                    boolean selection = false;
                    boolean backwardSelection = false;
                    int start = target.getCaretPosition();
                    int end = start;
                    
                    // check if there is a selection
                    if (Utilities.isSelectionShowing(caret)) {
                        int selStart = caret.getDot();
                        int selEnd = caret.getMark();
                        start = Math.min(selStart, selEnd);
                        end =   Math.max(selStart, selEnd) - 1;
                        selection = true;
                        backwardSelection = (selStart >= selEnd);
                    }

                    int zeroBaseStartLineNumber = rootElement.getElementIndex(start);
                    int zeroBaseEndLineNumber = rootElement.getElementIndex(end);

                    if (zeroBaseEndLineNumber == -1) {
                        // could not get line number
                        target.getToolkit().beep();
                    } else {
                        try {
                            // get line text
                            Element startLineElement = rootElement.getElement(zeroBaseStartLineNumber);
                            int startLineStartOffset = startLineElement.getStartOffset();

                            Element endLineElement = rootElement.getElement(zeroBaseEndLineNumber);
                            int endLineEndOffset = endLineElement.getEndOffset();
                            if (endLineEndOffset > doc.getLength()) {
                                return;
                            }

                            String linesText = doc.getText(startLineStartOffset, (endLineEndOffset - startLineStartOffset));

                            Element nextLineElement = rootElement.getElement(zeroBaseEndLineNumber + 1);
                            int nextLineEndOffset = nextLineElement.getEndOffset();

                            int column = start - startLineStartOffset;

                            // insert it after next line
                            if (nextLineEndOffset > doc.getLength()) {
                                doc.insertString(doc.getLength(), "\n" + linesText.substring(0, linesText.length()-1), null);
                            } else {
                                doc.insertString(nextLineEndOffset, linesText, null);
                            }

                            // remove original line
                            removeLineByLine(doc, startLineStartOffset, (endLineEndOffset - startLineStartOffset));
                            if (selection) {
                                // select moved lines
                                if (backwardSelection) {
                                    if (doc.getLength() <  nextLineEndOffset) {
                                        caret.setDot(doc.getLength()  - (endLineEndOffset - startLineStartOffset) + column + 1);
                                        caret.moveDot(doc.getLength());
                                    } else {
                                        caret.setDot(nextLineEndOffset - (endLineEndOffset - startLineStartOffset) + column);
                                        caret.moveDot(nextLineEndOffset - (endLineEndOffset - end - 1));
                                    }
                                } else {
                                    caret.setDot(nextLineEndOffset - (endLineEndOffset - end - 1));
                                    caret.moveDot(nextLineEndOffset  - (endLineEndOffset - startLineStartOffset) + column);
                                }
                            } else {
                                // set caret position
                                target.setCaretPosition(Math.min(doc.getLength(), nextLineEndOffset + column - (endLineEndOffset - startLineStartOffset)));
                            }
                        } catch (BadLocationException ex) {
                            target.getToolkit().beep();
                        }
                    }
                } finally {
                    DocumentUtilities.setTypingModification(doc, false);
                }
            }
        });
    }
}
 
源代码20 项目: jdk8u-dev-jdk   文件: ElementTreePanel.java
@SuppressWarnings("LeakingThisInConstructor")
public ElementTreePanel(JTextComponent editor) {
    this.editor = editor;

    Document document = editor.getDocument();

    // Create the tree.
    treeModel = new ElementTreeModel(document);
    tree = new JTree(treeModel) {

        @Override
        public String convertValueToText(Object value, boolean selected,
                boolean expanded, boolean leaf,
                int row, boolean hasFocus) {
            // Should only happen for the root
            if (!(value instanceof Element)) {
                return value.toString();
            }

            Element e = (Element) value;
            AttributeSet as = e.getAttributes().copyAttributes();
            String asString;

            if (as != null) {
                StringBuilder retBuffer = new StringBuilder("[");
                Enumeration names = as.getAttributeNames();

                while (names.hasMoreElements()) {
                    Object nextName = names.nextElement();

                    if (nextName != StyleConstants.ResolveAttribute) {
                        retBuffer.append(" ");
                        retBuffer.append(nextName);
                        retBuffer.append("=");
                        retBuffer.append(as.getAttribute(nextName));
                    }
                }
                retBuffer.append(" ]");
                asString = retBuffer.toString();
            } else {
                asString = "[ ]";
            }

            if (e.isLeaf()) {
                return e.getName() + " [" + e.getStartOffset() + ", " + e.
                        getEndOffset() + "] Attributes: " + asString;
            }
            return e.getName() + " [" + e.getStartOffset() + ", " + e.
                    getEndOffset() + "] Attributes: " + asString;
        }
    };
    tree.addTreeSelectionListener(this);
    tree.setDragEnabled(true);
    // Don't show the root, it is fake.
    tree.setRootVisible(false);
    // Since the display value of every node after the insertion point
    // changes every time the text changes and we don't generate a change
    // event for all those nodes the display value can become off.
    // This can be seen as '...' instead of the complete string value.
    // This is a temporary workaround, increase the needed size by 15,
    // hoping that will be enough.
    tree.setCellRenderer(new DefaultTreeCellRenderer() {

        @Override
        public Dimension getPreferredSize() {
            Dimension retValue = super.getPreferredSize();
            if (retValue != null) {
                retValue.width += 15;
            }
            return retValue;
        }
    });
    // become a listener on the document to update the tree.
    document.addDocumentListener(this);

    // become a PropertyChangeListener to know when the Document has
    // changed.
    editor.addPropertyChangeListener(this);

    // Become a CaretListener
    editor.addCaretListener(this);

    // configure the panel and frame containing it.
    setLayout(new BorderLayout());
    add(new JScrollPane(tree), BorderLayout.CENTER);

    // Add a label above tree to describe what is being shown
    JLabel label = new JLabel("Elements that make up the current document",
            SwingConstants.CENTER);

    label.setFont(new Font("Dialog", Font.BOLD, 14));
    add(label, BorderLayout.NORTH);

    setPreferredSize(new Dimension(400, 400));
}