下面列出了怎么用javax.swing.text.Document的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
}
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);
}
}
@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;
}
});
}
@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();
}
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;
}
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};
}
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;
}
@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;
}
@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;
}
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];
}
}
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);
}
/** 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;
}
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());
}
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;
}
@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();
}
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();
}
}
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);
}
}
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;
}
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);
}
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();
}
private void update(DocumentEvent evt) {
int index = browsersList.getSelectedIndex();
Document doc = evt.getDocument();
if (doc.equals(nameTextField.getDocument())) {
browsersModel.setBrowserName(index, nameTextField.getText());
}
}
/**
*
* @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);
}
});
}
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;
}
@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();
}
}
@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;
}
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());
}
@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;
}
@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();
}
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();
// }
};
}