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

The following examples show how to use javax.swing.text.JTextComponent#setCaretPosition() . 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: AbstractCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void doSubstituteText(JTextComponent c, BaseDocument d, String text) throws BadLocationException {
    int offset = getSubstOffset();
    String old = d.getText(offset, length);
    int nextOffset = ctx.getNextCaretPos();
    Position p = null;
    
    if (nextOffset >= 0) {
        p = d.createPosition(nextOffset);
    }
    if (text.equals(old)) {
        if (p != null) {
            c.setCaretPosition(p.getOffset());
        } else {
            c.setCaretPosition(offset + getCaretShift(d));
        }
    } else {
        d.remove(offset, length);
        d.insertString(offset, text, null);
        if (p != null) {
            c.setCaretPosition(p.getOffset());
        } else {
            c.setCaretPosition(offset + getCaretShift(d));
        }
    }
}
 
Example 2
Source File: MapCompletionAction.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sDoc,
        int dot, ActionEvent e) {
    Token token = sDoc.getTokenAt(dot);
    if (token != null) {
        String abbriv = ActionUtils.getTokenStringAt(sDoc, dot);
        if (completions.containsKey(abbriv)) {
            String completed = completions.get(abbriv);
            if (completed.indexOf('|') >= 0) {
                int ofst = completed.length() - completed.indexOf('|') - 1;
                sDoc.replaceToken(token, completed.replace("|", ""));
                target.setCaretPosition(target.getCaretPosition() - ofst);
            } else {
                sDoc.replaceToken(token, completed);
            }
        }
    }
}
 
Example 3
Source File: DialogEditor.java    From ET_Redux with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param focusEvent
 */
@Override
public void focusLost(FocusEvent focusEvent) {
    // revised nov 2010 to differentiate //added sep 2010 to handle accidentally blanked out number items
    JTextComponent temp = ((JTextComponent) focusEvent.getSource());

    if (temp.getText().length() == 0) {
        if ((temp.getDocument() instanceof DoubleDocument)//
                ||//
                (temp.getDocument() instanceof BigDecimalDocument)) {
            temp.setText("0.0");
        } else if ((temp.getDocument() instanceof IntegerDocument)) {
            temp.setText("0");
        }
    }

    temp.setCaretPosition(0);
}
 
Example 4
Source File: SwingUtil.java    From jlibs with Apache License 2.0 5 votes vote down vote up
/**
 * sets text of textComp without moving its caret.
 *
 * @param textComp  text component whose text needs to be set
 * @param text      text to be set. null will be treated as empty string
 */
public static void setText(JTextComponent textComp, String text){
    if(text==null)
        text = "";
    
    if(textComp.getCaret() instanceof DefaultCaret){
        DefaultCaret caret = (DefaultCaret)textComp.getCaret();
        int updatePolicy = caret.getUpdatePolicy();
        caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
        try{
            textComp.setText(text);
        }finally{
            caret.setUpdatePolicy(updatePolicy);
        }
    }else{
        int mark = textComp.getCaret().getMark();
        int dot = textComp.getCaretPosition();
        try{
            textComp.setText(text);
        }finally{
            int len = textComp.getDocument().getLength();
            if(mark>len)
                mark = len;
            if(dot>len)
                dot = len;
            textComp.setCaretPosition(mark);
            if(dot!=mark)
                textComp.moveCaretPosition(dot);
        }
    }
}
 
Example 5
Source File: IntelliJExpandableSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void copyCaretPosition(JTextComponent source, JTextComponent destination) {
  try {
    destination.setCaretPosition(source.getCaretPosition());
  }
  catch (Exception ignored) {
  }
}
 
Example 6
Source File: PairAction.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sDoc,
        int dot, ActionEvent e) {
    String left = e.getActionCommand();
    String right = PAIRS.get(left);
    String selected = target.getSelectedText();
    if (selected != null) {
        target.replaceSelection(left + selected + right);
    } else {
        target.replaceSelection(left + right);
        target.setCaretPosition(target.getCaretPosition() - right.length());
    }
}
 
Example 7
Source File: QuickFindDialog.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
private void updateFind() {
    JTextComponent t = target.get();
    DocumentSearchData d = dsd.get();
    String toFind = jTxtFind.getText();
    if (toFind == null || toFind.isEmpty()) {
        jLblStatus.setText(null);
        return;
    }
    try {
        d.setWrap(jChkWrap.isSelected());
        d.setPattern(toFind,
                jChkRegExp.isSelected(),
                jChkIgnoreCase.isSelected());
        // The dsd doFindNext will always find from current pos,
        // so we need to relocate to our saved pos before we call doFindNext
        jLblStatus.setText(null);
        t.setCaretPosition(oldCaretPosition);
        if (!d.doFindNext(t)) {
            jLblStatus.setText(java.util.ResourceBundle.getBundle("jsyntaxpane/Bundle").getString("QuickFindDialog.NotFound"));
        } else {
            jLblStatus.setText(null);
        }
        setSize(getPreferredSize());
        pack();
    } catch (PatternSyntaxException e) {
        jLblStatus.setText(e.getDescription());
    }
}
 
Example 8
Source File: PairAction.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 left = e.getActionCommand();
        String right = PAIRS.get(left);
        String selected = target.getSelectedText();
        if (selected != null) {
            target.replaceSelection(left + selected + right);
        } else {
            target.replaceSelection(left + right);
        }
        target.setCaretPosition(target.getCaretPosition() - 1);
    }
}
 
Example 9
Source File: StrutsConfigHyperlinkProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NbBundle.Messages({
        "lbl.goto.formbean.not.found=ActionForm Bean {0} not found."
    })
private void findForm(String name, BaseDocument doc){
    ExtSyntaxSupport sup = (ExtSyntaxSupport)doc.getSyntaxSupport();
    
    int offset = findDefinitionInSection(sup, "form-beans", "form-bean", "name", name);
    if (offset > 0){
        JTextComponent target = Utilities.getFocusedComponent();
        target.setCaretPosition(offset);
    } else {
        StatusDisplayer.getDefault().setStatusText(Bundle.lbl_goto_formbean_not_found(name));
    }
}
 
Example 10
Source File: EndTagAutocompletionResultItem.java    From netbeans with Apache License 2.0 5 votes vote down vote up
boolean replaceText( JTextComponent component, String text, int offset, int len) {
    boolean replaced = super.replaceText(component, text, offset, len);
    if(replaced) {
        //shift the cursor between tags
        component.setCaretPosition(offset);
    }
    return replaced;
}
 
Example 11
Source File: TextActions.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
	JTextComponent target = getTextComponent(e);
	if (target != null) {
		Document doc = target.getDocument();
		target.setCaretPosition(0);
		target.moveCaretPosition(doc.getLength());
	}
}
 
Example 12
Source File: ProjectInfoPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void setPlainText(JTextComponent field, String value, boolean loading) {
    if (value == null) {
        if (loading) {
            field.setText(LBL_Loading());
        } else {
            field.setText(LBL_Undefined());
        }
    } else {
        field.setText(value);
        field.setCaretPosition(0);
    }
}
 
Example 13
Source File: AquaTextFieldFormattedUI.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void mouseClicked(final MouseEvent e) {
    if (e.getClickCount() != 1) return;

    final JTextComponent c = getComponent();
    // apparently, focus has already been granted by the time this mouse listener fires
//    if (c.hasFocus()) return;

    c.setCaretPosition(viewToModel(c, e.getPoint()));
}
 
Example 14
Source File: JumpToPairAction.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sdoc,
        int dot, ActionEvent e) {
    Token current = sdoc.getTokenAt(dot);
    if (current == null) {
        return;
    }

    Token pair = sdoc.getPairFor(current);
    if (pair != null) {
        target.setCaretPosition(pair.start);
    }
}
 
Example 15
Source File: JspHyperlinkProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void navigateToUserBeanDef(Document doc, JspSyntaxSupport jspSup,
        JTextComponent target, String bean)
        throws BadLocationException {
    String text = doc.getText(0, doc.getLength());
    int index = text.indexOf(bean);
    TokenHierarchy tokenHierarchy = TokenHierarchy.get(doc);
    TokenSequence tokenSequence = tokenHierarchy.tokenSequence();

    while (index > 0) {
        tokenSequence.move(index);
        if (!tokenSequence.moveNext() && !tokenSequence.movePrevious()) {
            return; //no token found
        }
        Token token = tokenSequence.token();

        if (token.id() == JspTokenId.ATTR_VALUE) {

            while (!(token.id() == JspTokenId.ATTRIBUTE
                    && (token.text().toString().equals("class")
                    || token.text().toString().equals("type")))
                    && !(token.id() == JspTokenId.SYMBOL
                    && token.text().toString().equals("/>")) && tokenSequence.moveNext()) {
                token = tokenSequence.token();
            }

            if (tokenSequence.index() != -1 && token.id() == JspTokenId.SYMBOL) {
                while (!(token.id() == JspTokenId.ATTRIBUTE
                        && (token.text().toString().equals("class")
                        || token.text().toString().equals("type")))
                        && !(token.id() != JspTokenId.SYMBOL
                        && token.text().toString().equals("<")) && tokenSequence.movePrevious()) {
                    token = tokenSequence.token();
                }
            }

            if (tokenSequence.index() != -1 && token.id() == JspTokenId.ATTRIBUTE) {
                while (token.id() != JspTokenId.ATTR_VALUE && tokenSequence.moveNext()) {
                    token = tokenSequence.token();
                }
            }

            if (tokenSequence.index() != -1 && token.id() == JspTokenId.ATTR_VALUE) {
                target.setCaretPosition(token.offset(tokenHierarchy) + 1);
                break;
            }
        }
        index = text.indexOf(bean, index + bean.length());
    }
}
 
Example 16
Source File: ManageTags.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void setText (JTextComponent comp, String text) {
    comp.setText(text);
    comp.setCaretPosition(comp.getText().length());
    comp.moveCaretPosition(0);
}
 
Example 17
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 18
Source File: EditorFindSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
boolean replaceImpl(Map<String, Object> props, boolean oppositeDir, JTextComponent c) throws BadLocationException {
    props = getValidFindProperties(props);
    boolean back = Boolean.TRUE.equals(props.get(FIND_BACKWARD_SEARCH));
    if (oppositeDir) {
        back = !back;
    }
    boolean blockSearch = Boolean.TRUE.equals(props.get(FIND_BLOCK_SEARCH));
    Position blockSearchStartPos = (Position) props.get(FIND_BLOCK_SEARCH_START);
    int blockSearchStartOffset = (blockSearchStartPos != null) ? blockSearchStartPos.getOffset() : -1;

    if (c != null) {
        String s = (String)props.get(FIND_REPLACE_WITH);
        Caret caret = c.getCaret();
        if (caret.isSelectionVisible() && caret.getDot() != caret.getMark()){
            Object dp = props.get(FIND_BACKWARD_SEARCH);
            boolean direction = (dp != null) ? ((Boolean)dp).booleanValue() : false;
            int dotPos = (oppositeDir ^ direction ? c.getSelectionEnd() : c.getSelectionStart());
            c.setCaretPosition(dotPos);
        }
        
        FindReplaceResult result = findReplaceImpl(s, props, oppositeDir, c);
        if (result!=null){
            s  = result.getReplacedString();
        } else {
            return false;
        }

        Document doc = c.getDocument();
        int startOffset = c.getSelectionStart();
        int len = c.getSelectionEnd() - startOffset;
        DocUtils.atomicLock(doc);
        try {
            if (len > 0) {
                doc.remove(startOffset, len);
            }
            if (s != null && s.length() > 0) {
                try {
                    NavigationHistory.getEdits().markWaypoint(c, startOffset, false, true);
                } catch (BadLocationException e) {
                    LOG.log(Level.WARNING, "Can't add position to the history of edits.", e); //NOI18N
                }
                doc.insertString(startOffset, s, null);
                if (startOffset == blockSearchStartOffset) { // Replaced at begining of block
                    blockSearchStartPos = doc.createPosition(startOffset);
                    props.put(EditorFindSupport.FIND_BLOCK_SEARCH_START, blockSearchStartPos);
                }
            }
        } finally {
            DocUtils.atomicUnlock(doc);
            if (blockSearch){
                setBlockSearchHighlight(blockSearchStartOffset, getBlockEndOffset());
            }
        }
        
        // adjust caret pos after replace operation
        int adjustedCaretPos = (back || s == null) ? startOffset : startOffset + s.length();
        caret.setDot(adjustedCaretPos);
        
    }
    
    return true;
}
 
Example 19
Source File: NextCamelCasePosition.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void moveToNewOffset(JTextComponent textComponent, int offset) throws BadLocationException {
    textComponent.setCaretPosition(offset);
}
 
Example 20
Source File: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Sets the caret position of the given target to the given line and column
 * @param target
 * @param line the first being 1
 * @param column the first being 1
 */
public static void setCaretPosition(JTextComponent target, int line, int column) {
	int p = getDocumentPosition(target, line, column);
	target.setCaretPosition(p);
}