Java Code Examples for javax.swing.text.JTextComponent#getCaretPosition()

The following examples show how to use javax.swing.text.JTextComponent#getCaretPosition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoToDeclarationAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: STViz.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
    }
}
 
Example 3
Source File: BasicValuesCompletionItem.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
@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);

        }
    }

}
 
Example 4
Source File: GoToSuperTypeAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 5
Source File: JspCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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();
        }

    }
 
Example 6
Source File: HistoryCompletionProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 7
Source File: STViz.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
    }
}
 
Example 8
Source File: HistoryCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: UndoRedoSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 10
Source File: CAccessibleText.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: DelegateMethodGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: HtmlPaletteCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 13
Source File: CssActionsImplementationProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 14
Source File: CAccessibleText.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 15
Source File: CPActionsImplementationProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: RectangularSelectionUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 17
Source File: JavaIndentAction.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 18
Source File: CAccessibleText.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 19
Source File: SpringXMLConfigCompletionItem.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 20
Source File: ActionFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
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
    }
}