下面列出了javax.swing.text.JTextComponent#getCaretPosition ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void highlight(JTextComponent comp, int i, int j, boolean scroll) {
Highlighter highlighter = comp.getHighlighter();
highlighter.removeAllHighlights();
try {
i = toComponentPosition(comp, i);
j = toComponentPosition(comp, j);
highlighter.addHighlight(i, j+1, DefaultHighlighter.DefaultPainter);
if ( scroll ) {
if ( comp.getCaretPosition()< i || comp.getCaretPosition()>j ) {
comp.moveCaretPosition(i);
comp.scrollRectToVisible(comp.modelToView(i));
}
}
}
catch (BadLocationException ble) {
errMgr.internalError(tmodel.root.event.scope.st, "bad highlight location", ble);
}
}
protected void highlight(JTextComponent comp, int i, int j, boolean scroll) {
Highlighter highlighter = comp.getHighlighter();
highlighter.removeAllHighlights();
try {
i = toComponentPosition(comp, i);
j = toComponentPosition(comp, j);
highlighter.addHighlight(i, j+1, DefaultHighlighter.DefaultPainter);
if ( scroll ) {
if ( comp.getCaretPosition()< i || comp.getCaretPosition()>j ) {
comp.moveCaretPosition(i);
comp.scrollRectToVisible(comp.modelToView(i));
}
}
}
catch (BadLocationException ble) {
errMgr.internalError(tmodel.root.event.scope.st, "bad highlight location", ble);
}
}
static int isFirstJavaLine(JTextComponent component) {
ShellSession s = ShellSession.get(component.getDocument());
if (s == null) {
return -1;
}
ConsoleSection sec = s.getModel().getInputSection();
if (sec == null) {
return -1;
}
LineDocument ld = LineDocumentUtils.as(component.getDocument(), LineDocument.class);
if (ld == null) {
return -1;
}
int off = sec.getStart();
int caret = component.getCaretPosition();
int s1 = LineDocumentUtils.getLineStart(ld, caret);
int s2 = LineDocumentUtils.getLineStart(ld, off);
try {
return s1 == s2 ?
component.getDocument().getText(sec.getPartBegin(), sec.getPartLen()).trim().length()
: -1;
} catch (BadLocationException ex) {
return 0;
}
}
private void reindent(JTextComponent component) {
final BaseDocument doc = (BaseDocument) component.getDocument();
final int dotPos = component.getCaretPosition();
final Indent indent = Indent.get(doc);
indent.lock();
try {
doc.runAtomic(new Runnable() {
public void run() {
try {
int startOffset = Utilities.getRowStart(doc, dotPos);
int endOffset = Utilities.getRowEnd(doc, dotPos);
indent.reindent(startOffset, endOffset);
} catch (BadLocationException ex) {
//ignore
}
}
});
} finally {
indent.unlock();
}
}
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
final JavaSource js = JavaSource.forDocument(target.getDocument());
if (js == null) {
StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(GoToSupport.class, "WARN_CannotGoToGeneric",1));
return;
}
final int caretPos = target.getCaretPosition();
final AtomicBoolean cancel = new AtomicBoolean();
ProgressUtils.runOffEventDispatchThread(new Runnable() {
@Override
public void run() {
goToImpl(target, js, caretPos, cancel);
}
}, NbBundle.getMessage(JavaKit.class, "goto-super-implementation"), cancel, false);
}
@Override
public void defaultAction(JTextComponent component) {
if (component != null) {
try {
BaseDocument document = (BaseDocument) component.getDocument();
int caretPosition = component.getCaretPosition();
int startPosition = caretPosition - 1;
while ('\"' != (document.getChars(startPosition, 1)[0])) {
startPosition--;
}
startPosition++;
document.replace(startPosition, caretPosition - startPosition, completionText, null);
Completion.get().hideAll();
RankingProvider.inserted(completionText.hashCode());
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
}
public boolean isEnabled() {
JTextComponent comp = getTextComponent(null);
if (comp == null)
return false;
ASTNode node = getASTNode(comp);
if (node == null)
return false;
int position = comp.getCaretPosition();
ASTPath path = node.findPath(position);
if (path == null)
return false;
DatabaseContext root = DatabaseManager.getRoot((ASTNode) path.getRoot());
if (root == null)
return false;
DatabaseItem item = root.getDatabaseItem (path.getLeaf ().getOffset ());
return item != null;
}
static int getLineNumberForIndex(final Accessible a, int index) {
final Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return -1;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
// treat -1 special, returns the current caret position
if (index == -1) index = jc.getCaretPosition();
// Determine line number (can be -1)
return root.getElementIndex(index);
}
public void actionPerformed(ActionEvent e) {
JTextComponent target = getTextComponent(e);
if (target != null) {
String line = ActionUtils.getLine(target);
String prefix = ActionUtils.getIndent(line);
Integer tabSize = (Integer) target.getDocument().getProperty(PlainDocument.tabSizeAttribute);
if (line.trim().endsWith("{")) {
prefix += ActionUtils.SPACES.substring(0, tabSize);
}
SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target);
if (sDoc != null && line.trim().equals("}")) {
int pos = target.getCaretPosition();
int start = sDoc.getParagraphElement(pos).getStartOffset();
int end = sDoc.getParagraphElement(pos).getEndOffset();
if (end >= sDoc.getLength()) {
end--;
}
if (line.startsWith(ActionUtils.SPACES.substring(0, tabSize))) {
try {
sDoc.replace(start, end - start, line.substring(tabSize) + "\n", null);
} catch (BadLocationException ex) {
Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
} else {
target.replaceSelection("\n" + prefix);
}
} else {
target.replaceSelection("\n" + prefix);
}
}
}
public static void resetRectangularSelection(JTextComponent c) {
c.getCaretPosition();
c.putClientProperty(RECTANGULAR_SELECTION_REGIONS_PROPERTY, new ArrayList<Position>());
boolean value = !isRectangularSelection(c);
RectangularSelectionUtils.setRectangularSelection(c, Boolean.valueOf(value) );
RectangularSelectionUtils.setRectangularSelection(c, Boolean.valueOf(!value));
}
public TextComponentTask(EditorCookie ec) {
JTextComponent textC = ec.getOpenedPanes()[0];
this.document = textC.getDocument();
this.caretOffset = textC.getCaretPosition();
this.selectionStart = textC.getSelectionStart();
this.selectionEnd = textC.getSelectionEnd();
}
static int getLineNumberForIndex(final Accessible a, int index) {
final Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return -1;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
// treat -1 special, returns the current caret position
if (index == -1) index = jc.getCaretPosition();
// Determine line number (can be -1)
return root.getElementIndex(index);
}
static ShellSession checkInputSection(JTextComponent component) {
Document doc = component.getDocument();
ShellSession session = ShellSession.get(doc);
if (session == null) {
return null;
}
ConsoleModel model = session.getModel();
if (model == null) {
return null;
}
ConsoleSection is = model.getInputSection();
if (is == null) {
return null;
}
LineDocument ld = LineDocumentUtils.as(doc, LineDocument.class);
if (ld == null) {
return null;
}
int caret = component.getCaretPosition();
int lineStart = is.getPartBegin();
try {
int lineEnd = LineDocumentUtils.getLineEnd(ld, caret);
if (caret < lineStart || caret > lineEnd) {
return null;
}
} catch (BadLocationException ex) {
return null;
}
return session;
}
public TextComponentTask(EditorCookie ec) {
JTextComponent textC = ec.getOpenedPanes()[0];
this.document = textC.getDocument();
this.caretOffset = textC.getCaretPosition();
this.selectionStart = textC.getSelectionStart();
this.selectionEnd = textC.getSelectionEnd();
}
@Override
public void defaultAction(JTextComponent component) {
try {
//first remove the typed prefix
Document doc = component.getDocument();
int currentCaretPosition = component.getCaretPosition();
doc.remove(completionExpressionStartOffset, currentCaretPosition - completionExpressionStartOffset);
Completion.get().hideAll();
action.actionPerformed(null);
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
public static ElementNode.Description getAvailableMethods(final JTextComponent component, final ElementHandle<? extends TypeElement> typeElementHandle, final ElementHandle<? extends VariableElement> fieldHandle) {
if (fieldHandle.getKind().isField()) {
final JavaSource js = JavaSource.forDocument(component.getDocument());
if (js != null) {
final int caretOffset = component.getCaretPosition();
final ElementNode.Description[] description = new ElementNode.Description[1];
final AtomicBoolean cancel = new AtomicBoolean();
ProgressUtils.runOffEventDispatchThread(new Runnable() {
@Override
public void run() {
try {
ScanUtils.waitUserActionTask(js, new Task<CompilationController>() {
@Override
public void run(CompilationController controller) throws IOException {
if (controller.getPhase().compareTo(Phase.RESOLVED) < 0) {
Phase phase = controller.toPhase(Phase.RESOLVED);
if (phase.compareTo(Phase.RESOLVED) < 0) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, "Cannot reach required phase. Leaving without action.");
}
return;
}
}
if (cancel.get()) {
return;
}
description[0] = getAvailableMethods(controller, caretOffset, typeElementHandle, fieldHandle);
}
});
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
}
}, NbBundle.getMessage(DelegateMethodGenerator.class, "LBL_Get_Available_Methods"), cancel, false);
cancel.set(true);
return description[0];
}
}
return null;
}
static int getLineNumberForIndex(final Accessible a, int index) {
final Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return -1;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
// treat -1 special, returns the current caret position
if (index == -1) index = jc.getCaretPosition();
// Determine line number (can be -1)
return root.getElementIndex(index);
}
private void startNewEdit (JTextComponent component, UndoableEdit atomicEdit) {
if (edit != null) {
// finish the last edit
edit.end();
}
edit = new MyCompoundEdit();
edit.addEdit(atomicEdit);
super.undoableEditHappened(new UndoableEditEvent(component, edit));
lastOffset = component.getCaretPosition();
lastLength = component.getDocument().getLength();
}
public void actionPerformed(ActionEvent evt, JTextComponent target) {
AbstractDocument adoc = (AbstractDocument)target.getDocument();
// Dump fold hierarchy
FoldHierarchy hierarchy = FoldHierarchy.get(target);
adoc.readLock();
try {
hierarchy.lock();
try {
/*DEBUG*/System.err.println("FOLD HIERARCHY DUMP:\n" + hierarchy); // NOI18N
TokenHierarchy<?> th = TokenHierarchy.get(adoc);
/*DEBUG*/System.err.println("TOKEN HIERARCHY DUMP:\n" + (th != null ? th : "<NULL-TH>")); // NOI18N
} finally {
hierarchy.unlock();
}
} finally {
adoc.readUnlock();
}
View rootView = null;
TextUI textUI = target.getUI();
if (textUI != null) {
rootView = textUI.getRootView(target); // Root view impl in BasicTextUI
if (rootView != null && rootView.getViewCount() == 1) {
rootView = rootView.getView(0); // Get DocumentView
}
}
if (rootView != null) {
String rootViewDump = (rootView instanceof DocumentView)
? ((DocumentView)rootView).toStringDetail()
: rootView.toString();
/*DEBUG*/System.err.println("DOCUMENT VIEW: " + System.identityHashCode(rootView) + // NOI18N
"\n" + rootViewDump); // NOI18N
int caretOffset = target.getCaretPosition();
int caretViewIndex = rootView.getViewIndex(caretOffset, Position.Bias.Forward);
/*DEBUG*/System.err.println("caretOffset=" + caretOffset + ", caretViewIndex=" + caretViewIndex); // NOI18N
if (caretViewIndex >= 0 && caretViewIndex < rootView.getViewCount()) {
View caretView = rootView.getView(caretViewIndex);
/*DEBUG*/System.err.println("caretView: " + caretView); // NOI18N
}
/*DEBUG*/System.err.println(FixLineSyntaxState.lineInfosToString(adoc));
// Check the hierarchy correctness
//org.netbeans.editor.view.spi.ViewUtilities.checkViewHierarchy(rootView);
}
if (adoc instanceof BaseDocument) {
/*DEBUG*/System.err.println("DOCUMENT:\n" + ((BaseDocument)adoc).toStringDetail()); // NOI18N
}
}
@Override
protected void substituteText(JTextComponent c, int offset, int len, String toAdd) {
super.substituteText(c, offset, len, toAdd);
int newCaretPos = c.getCaretPosition() - 1; // for achieving p:something-ref="|" on completion
c.setCaretPosition(newCaretPos);
}