javax.swing.text.AbstractDocument.AbstractElement#javax.swing.text.Document源码实例Demo

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

源代码1 项目: java-swing-tips   文件: MainPanel.java
private void append(String str) {
  Document doc = jtp.getDocument();
  String text;
  if (doc.getLength() > LIMIT) {
    timerStop();
    startButton.setEnabled(false);
    text = "doc.getLength()>1000";
  } else {
    text = str;
  }
  try {
    doc.insertString(doc.getLength(), text + LS, null);
    jtp.setCaretPosition(doc.getLength());
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
源代码2 项目: jeveassets   文件: TextManager.java
public static void installTextComponent(final JTextComponent component) {
	//Make sure this component does not already have a UndoManager
	Document document = component.getDocument();
	boolean found = false;
	if (document instanceof AbstractDocument) {
		AbstractDocument abstractDocument = (AbstractDocument) document;
		for (UndoableEditListener editListener : abstractDocument.getUndoableEditListeners()) {
			if (editListener.getClass().equals(CompoundUndoManager.class)) {
				CompoundUndoManager undoManager = (CompoundUndoManager) editListener;
				undoManager.reset();
				return;
			}
		}
	}
	if (!found) {
		new TextManager(component);
	}
}
 
源代码3 项目: netbeans   文件: BreadcrumbsController.java
@Deprecated
public static void setBreadcrumbs(@NonNull Document doc, @NonNull final Node root, @NonNull final Node selected) {
    Parameters.notNull("doc", doc);
    Parameters.notNull("root", root);
    Parameters.notNull("selected", selected);
    
    final ExplorerManager manager = HolderImpl.get(doc).getManager();

    Children.MUTEX.writeAccess(new Action<Void>() {
        @Override public Void run() {
            manager.setRootContext(root);
            manager.setExploredContext(selected);
            return null;
        }
    });
}
 
源代码4 项目: openjdk-8-source   文件: LWTextAreaPeer.java
@Override
public void replaceRange(final String text, final int start,
                         final int end) {
    synchronized (getDelegateLock()) {
        // JTextArea.replaceRange() posts two different events.
        // Since we make no differences between text events,
        // the document listener has to be disabled while
        // JTextArea.replaceRange() is called.
        final Document document = getTextComponent().getDocument();
        document.removeDocumentListener(this);
        getDelegate().getView().replaceRange(text, start, end);
        revalidate();
        postEvent(new TextEvent(getTarget(), TextEvent.TEXT_VALUE_CHANGED));
        document.addDocumentListener(this);
    }
    repaintPeer();
}
 
源代码5 项目: netbeans   文件: DiffResultsViewForLine.java
private Document getSourceDocument(StreamSource ss) {
    Document sdoc = null;
    FileObject fo = ss.getLookup().lookup(FileObject.class);
    if (fo != null) {
        try {
            DataObject dao = DataObject.find(fo);
            if (dao.getPrimaryFile() == fo) {
                EditorCookie ec = dao.getCookie(EditorCookie.class);
                if (ec != null) {
                    sdoc = ec.openDocument();
                }
            }
        } catch (Exception e) {
            // fallback to other means of obtaining the source
        }
    } else {
        sdoc = ss.getLookup().lookup(Document.class);
    }
    return sdoc;
}
 
源代码6 项目: netbeans   文件: XmlTokenList.java
protected int[] findNextSpellSpan() throws BadLocationException {
    TokenHierarchy<Document> h = TokenHierarchy.get((Document) doc);
    TokenSequence<?> ts = h.tokenSequence();
    if (ts == null || hidden) {
        return new int[]{-1, -1};
    }

    ts.move(nextSearchOffset);

    while (ts.moveNext()) {
        TokenId id = ts.token().id();

        if (id == XMLTokenId.BLOCK_COMMENT || id == XMLTokenId.TEXT) {
            return new int[]{ts.offset(), ts.offset() + ts.token().length()};
        }
    }
    return new int[]{-1, -1};
}
 
源代码7 项目: netbeans   文件: Util.java
public static Document setDocumentContentTo(Document doc, InputStream in) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    StringBuffer sbuf = new StringBuffer();
    try {
        String line = null;
        while ((line = br.readLine()) != null) {
            sbuf.append(line);
            sbuf.append(System.getProperty("line.separator"));
        }
    } finally {
        br.close();
    }
    doc.remove(0, doc.getLength());
    doc.insertString(0,sbuf.toString(),null);
    return doc;
}
 
源代码8 项目: netbeans   文件: YamlCompletion.java
@Override
public String getPrefix(ParserResult info, int caretOffset, boolean upToOffset) {
    if (caretOffset > 0) {
        try {
            Document doc = ((YamlParserResult) info).getSnapshot().getSource().getDocument(false);
            if (doc != null) {
                return doc.getText(caretOffset - 1, 1);
            } else {
                return null;
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    return null;
}
 
源代码9 项目: netbeans   文件: JavadocCompletionQuery.java
@Override
protected boolean canFilter(JTextComponent component) {
    final int newOffset = component.getSelectionStart();
    final Document doc = component.getDocument();
    if (newOffset > caretOffset && items != null && !items.isEmpty()) {
        try {
            String prefix = doc.getText(caretOffset, newOffset - caretOffset);
            if (!isJavaIdentifierPart(prefix)) {
                Completion.get().hideDocumentation();
                Completion.get().hideCompletion();
            }
        } catch (BadLocationException ble) {
        }
    }
    return false;
}
 
源代码10 项目: netbeans   文件: HintsControllerImpl.java
private static void computeLineSpan(Document doc, int[] offsets) throws BadLocationException {
    String text = doc.getText(offsets[0], offsets[1] - offsets[0]);
    int column = 0;
    int length = text.length();
    
    while (column < text.length() && Character.isWhitespace(text.charAt(column))) {
        column++;
    }
    
    while (length > 0 && Character.isWhitespace(text.charAt(length - 1)))
        length--;
    
    offsets[1]  = offsets[0] + length;
    offsets[0] += column;
    
    if (offsets[1] < offsets[0]) {
        //may happen on lines without non-whitespace characters
        offsets[0] = offsets[1];
    }
}
 
源代码11 项目: netbeans   文件: PlainDocumentTest.java
public void testBehaviour() throws Exception {
    Document doc = new PlainDocument();
    doc.insertString(0, "test hello world", null);
    UndoManager undo = new UndoManager();
    doc.addUndoableEditListener(undo);
    Position pos = doc.createPosition(2);
    doc.remove(0, 3);
    assert (pos.getOffset() == 0);
    undo.undo();
    assert (pos.getOffset() == 2);
    
    Position pos2 = doc.createPosition(5);
    doc.remove(4, 2);
    Position pos3 = doc.createPosition(4);
    assertSame(pos2, pos3);
    undo.undo();
    assert (pos3.getOffset() == 5);
}
 
源代码12 项目: netbeans   文件: Formatter.java
/** Should the typed tabs be expanded to the spaces? */
public boolean expandTabs() {
    Document doc = LegacyFormattersProvider.getFormattingContextDocument();
    if (doc != null) {
        Object ret = callIndentUtils("isExpandTabs", doc); //NOI18N
        if (ret instanceof Boolean) {
            return (Boolean) ret;
        }
    }

    if (!customExpandTabs && !inited) {
        prefsListener.preferenceChange(null);
    }

    return expandTabs;
}
 
源代码13 项目: netbeans   文件: UndoableEditWrapperTest.java
public void testWrapping() throws Exception {
        MimePath mimePath = MimePath.EMPTY;
        MockMimeLookup.setInstances(mimePath, new TestingUndoableEditWrapper(), new TestingUndoableEditWrapper2());
        CESEnv env = new CESEnv();
        Document doc = env.support.openDocument();
//        doc.addUndoableEditListener(new UndoableEditListener() {
//            @Override
//            public void undoableEditHappened(UndoableEditEvent e) {
//                UndoableEdit edit = e.getEdit();
//            }
//        });
        doc.insertString(0, "Test", null);
        Class wrapEditClass = TestingUndoableEditWrapper.WrapCompoundEdit.class;
        assertNotNull(NbDocument.getEditToBeUndoneOfType(env.support, wrapEditClass));
        Class wrapEditClass2 = TestingUndoableEditWrapper2.WrapCompoundEdit2.class;
        assertNotNull(NbDocument.getEditToBeUndoneOfType(env.support, wrapEditClass2));
        
        // A trick to get whole edit
        UndoableEdit wholeEdit = NbDocument.getEditToBeUndoneOfType(env.support, UndoableEdit.class);
        assertTrue(wholeEdit instanceof List);
        @SuppressWarnings("unchecked")
        List<? extends UndoableEdit> listEdit = (List<? extends UndoableEdit>) wholeEdit;
        assertEquals(3, listEdit.size());
        assertEquals(wrapEditClass, listEdit.get(1).getClass());
        assertEquals(wrapEditClass2, listEdit.get(2).getClass());
    }
 
源代码14 项目: 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;
}
 
源代码15 项目: openjdk-jdk8u   文件: LWTextComponentPeer.java
@Override
public final void setText(final String text) {
    synchronized (getDelegateLock()) {
        // JTextArea.setText() posts two different events (remove & insert).
        // Since we make no differences between text events,
        // the document listener has to be disabled while
        // JTextArea.setText() is called.
        final Document document = getTextComponent().getDocument();
        document.removeDocumentListener(this);
        getTextComponent().setText(text);
        revalidate();
        if (firstChangeSkipped) {
            postEvent(new TextEvent(getTarget(),
                                    TextEvent.TEXT_VALUE_CHANGED));
        }
        document.addDocumentListener(this);
    }
    repaintPeer();
}
 
源代码16 项目: netbeans   文件: TokenSequenceTest.java
public void testSubSequenceInUnfinishedTH() throws Exception {
    Document doc = new ModificationTextDocument();
    //             012345678
    String text = "ab cd efg";
    doc.insertString(0, text, null);
    
    doc.putProperty(Language.class,TestTokenId.language());
    TokenHierarchy<?> hi = TokenHierarchy.get(doc);

    ((AbstractDocument)doc).readLock();
    try {
        TokenSequence<?> ts = hi.tokenSequence();
        assertTrue(ts.moveNext());

        ts = ts.subSequence(2, 6);
        assertTrue(ts.moveNext());
        LexerTestUtilities.assertTokenEquals(ts,TestTokenId.WHITESPACE, " ", 2);
        assertTrue(ts.moveNext());
        LexerTestUtilities.assertTokenEquals(ts,TestTokenId.IDENTIFIER, "cd", 3);
        assertTrue(ts.moveNext());
        LexerTestUtilities.assertTokenEquals(ts,TestTokenId.WHITESPACE, " ", 5);
        assertFalse(ts.moveNext());
    } finally {
        ((AbstractDocument)doc).readUnlock();
    }
}
 
源代码17 项目: netbeans   文件: TextDocumentServiceImpl.java
private JavaSource getSource(String fileUri) {
    Document doc = openedDocuments.get(fileUri);
    if (doc == null) {
        try {
            FileObject file = fromUri(fileUri);
            return JavaSource.forFileObject(file);
        } catch (MalformedURLException ex) {
            return null;
        }
    } else {
        return JavaSource.forDocument(doc);
    }
}
 
源代码18 项目: netbeans   文件: CslTestBase.java
private static org.netbeans.modules.csl.core.Language getCompletableLanguage(Document doc, int offset) {
    BaseDocument baseDoc = (BaseDocument)doc;
    List<org.netbeans.modules.csl.core.Language> list = LanguageRegistry.getInstance().getEmbeddedLanguages(baseDoc, offset);
    for (org.netbeans.modules.csl.core.Language l : list) {
        if (l.getCompletionProvider() != null) {
            return l;
        }
    }

    return null;
}
 
源代码19 项目: netbeans   文件: EditHistoryTest.java
public void testMultipleInserts3() throws Exception {
    EditHistory history = new EditHistory();
    String original = "   HelloWorld";
    Document doc = getDocument(original);
    //012345678901234567890
    //   HelloWorld
    //   HelloWo__rld
    insert(doc, history, 10, "__");
    //012345678901234567890
    //   HelloWo__rld
    //   He__lloWo__rld
    insert(doc, history, 5, "__");
    //012345678901234567890
    //   He__lloWo__rld
    //   He__ll__oWo__rld
    insert(doc, history, 9, "__");

    String modified = doc.getText(0, doc.getLength());
    assertEquals("   He__ll__oWo__rld", modified);
    assertEquals(5, history.getStart());
    assertEquals(10, history.getOriginalEnd());
    assertEquals(16, history.getEditedEnd());
    assertEquals(5, history.getOriginalSize());
    assertEquals(11, history.getEditedSize());
    assertEquals(6, history.getSizeDelta());
    validateHistory(original, modified, history);
}
 
源代码20 项目: netbeans   文件: TestMethodUtil.java
public static SingleMethod getTestMethod(final Document doc, final int cursor) {
    final AtomicReference<SingleMethod> sm = new AtomicReference<>();
    if (doc != null) {

        Source s = Source.create(doc);
        try {
            ParserManager.parseWhenScanFinished(Collections.<Source>singleton(s), new UserTask() {
                @Override
                public void run(ResultIterator rit) throws Exception {
                    Result r = rit.getParserResult();
                    //0:line, 1:column
                    final int[] lc = getLineAndColumn(doc.getText(0, doc.getLength()), cursor);
                    final int line = lc[0];
                    final int col = lc[1];
                    final ModuleNode root = extractModuleNode(r);
                    final ClassNode cn = getClassNodeForLineAndColumn(root, line, col);
                    final MethodNode mn = getMethodNodeForLineAndColumn(cn, line, col);
                    if (mn != null) {
                        final SingleMethod lsm = new SingleMethod(s.getFileObject(), mn.getName());
                        sm.set(lsm);
                    }
                }

            });
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    return sm.get();
}
 
源代码21 项目: netbeans   文件: WebBrowsersOptionsPanel.java
private void update(DocumentEvent evt) {
    int index = browsersList.getSelectedIndex();
    Document doc = evt.getDocument();
    if (doc.equals(nameTextField.getDocument())) {
        browsersModel.setBrowserName(index, nameTextField.getText());
    } 
}
 
源代码22 项目: netbeans   文件: BreadcrumbsController.java
/**
 * 
 * @param doc
 * @param selected 
 * @since 1.8
 */
public static void setBreadcrumbs(@NonNull final Document doc, @NonNull final BreadcrumbsElement selected) {
    WORKER.post(new Runnable() {
        @Override public void run() {
            List<BreadcrumbsElement> path = new ArrayList<>();
            
            BreadcrumbsElement el = selected;
            
            while (el != null) {
                path.add(el);
                el = el.getParent();
            }
            
            Node root = new BreadCrumbsNodeImpl(path.remove(path.size() - 1));
            Node last = root;
            
            Collections.reverse(path);
           
            for (BreadcrumbsElement current : path) {
                for (Node n : last.getChildren().getNodes(true)) {
                    if (n.getLookup().lookup(BreadcrumbsElement.class) == current) {
                        last = n;
                        break;
                    }
                }
            }
            
            setBreadcrumbs(doc, root, last);
        }
    });
}
 
源代码23 项目: netbeans   文件: RuntimeCatalogModel.java
private ModelSource createModelSource(InputStream is) throws CatalogModelException{
    try {
        Document d = AbstractDocumentModel.getAccessProvider().loadSwingDocument(is);
        if(d != null)
            return new ModelSource(Lookups.fixed(new Object[]{this,d}), false);
    } catch (Exception ex) {
        throw new CatalogModelException(ex);
    }
            
    return null;
}
 
源代码24 项目: netbeans   文件: XMLKit.java
@Override
public Document createDefaultDocument() {
    if(J2EE_LEXER_COLORING) {
        Document doc = new XMLEditorDocument(getContentType());
        doc.putProperty(Language.class, XMLTokenId.language());
        return doc;
    } else {
        return super.createDefaultDocument();
    }
}
 
源代码25 项目: netbeans   文件: EventSupport.java
@Override
public Document readDocument(FileObject fileObject, boolean forceOpen) {
    EditorCookie ec = null;
    
    try {
        DataObject dataObject = DataObject.find (fileObject);
        ec = dataObject.getLookup ().lookup (EditorCookie.class);
    } catch (DataObjectNotFoundException ex) {
        //DataobjectNotFoundException may happen in case of deleting opened file
        //handled by returning null
    }

    if (ec == null) return null;
    Document doc = ec.getDocument ();
    if (doc == null && forceOpen) {
        try {
            try {
                doc = ec.openDocument ();
            } catch (UserQuestionException uqe) {
                uqe.confirmed ();
                doc = ec.openDocument ();
            }
        } catch (IOException ioe) {
            LOGGER.log (Level.WARNING, null, ioe);
        }
    }
    return doc;
}
 
源代码26 项目: netbeans   文件: SQLCompletionEnv.java
private static String getDocumentText(final Document doc) {
    final String[] result = { null };
    doc.render(new Runnable() {
        public void run() {
            try {
                result[0] = doc.getText(0, doc.getLength());
            } catch (BadLocationException e) {
                // Should not happen.
            }
        }
    });
    return result[0];
}
 
@Override
public void init(SaasMethod m, Document doc) throws IOException {
    super.init(m, new CustomClientSaasBean((CustomSaasMethod) m, true), doc);
    
    this.j2eeAuthGen = new SaasClientJ2eeAuthenticationGenerator(getBean(), getProject());
    this.j2eeAuthGen.setLoginArguments(getLoginArguments());
    this.j2eeAuthGen.setAuthenticatorMethodParameters(getAuthenticatorMethodParameters());
    this.j2eeAuthGen.setSaasServiceFolder(getSaasServiceFolder());
    this.j2eeAuthGen.setAuthenticationProfile(getBean().getProfile(m, getDropFileType()));
    this.j2eeAuthGen.setDropFileType(getDropFileType());
}
 
源代码28 项目: visualvm   文件: ThreadDumpView.java
@Override
public Document createDefaultDocument() {
    StyleSheet styles = getStyleSheet();
    StyleSheet ss = new StyleSheet();

    ss.addStyleSheet(styles);

    HTMLDocument doc = new CustomHTMLDocument(ss);
    doc.setParser(getParser());
    doc.setAsynchronousLoadPriority(4);
    doc.setTokenThreshold(100);
    return doc;
}
 
源代码29 项目: netbeans   文件: SoapClientPojoCodeGenerator.java
@Override
public void init(SaasMethod m, Document doc) throws IOException {
    super.init(m, doc);
    WsdlSaasMethod wsm = (WsdlSaasMethod) m;
    Project p = FileOwnerQuery.getOwner(NbEditorUtilities.getFileObject(doc));
    SaasBean bean = new SoapClientSaasBean(wsm, p, JavaUtil.toJaxwsOperationInfos(wsm, p));
    setBean(bean);
    clearVariablePatterns();
}
 
源代码30 项目: netbeans   文件: NbEditorUI.java
public NbEditorUI() {
        focusL = new FocusAdapter() {
            public @Override void focusGained(FocusEvent evt) {
                // Refresh file object when component made active
                Document doc = getDocument();
                if (doc != null) {
                    DataObject dob = NbEditorUtilities.getDataObject(doc);
                    if (dob != null) {
                        final FileObject fo = dob.getPrimaryFile();
                        if (fo != null) {
                            // Fixed #48151 - posting the refresh outside of AWT thread
                            synchronized (lock) {
                                objectsToRefresh.add(fo);
                            }
                            TASK.schedule(0);
                        }
                    }
                }

//                // Check if editor is docked and if so then use global status bar.
//                JTextComponent component = getComponent();
//                // Check if component is inside main window
//                boolean underMainWindow = (SwingUtilities.isDescendingFrom(component,
//                WindowManager.getDefault().getMainWindow()));
//                getStatusBar().setVisible(!underMainWindow); // Note: no longer checking the preferences settting
            }

//            @Override
//            public void focusLost(FocusEvent e) {
//                // Clear global panel
//                StatusLineFactories.clearStatusLine();
//            }


        };
    }