下面列出了javax.swing.text.JTextComponent#setCaretPosition ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
* @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);
}
@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);
}
}
}
}
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));
}
}
}
@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);
}
}
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()));
}
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);
}
}
@Override
public void actionPerformed(ActionEvent e) {
JTextComponent target = getTextComponent(e);
if (target != null) {
Document doc = target.getDocument();
target.setCaretPosition(0);
target.moveCaretPosition(doc.getLength());
}
}
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;
}
@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));
}
}
/**
* 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);
}
}
}
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);
}
}
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());
}
}
@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());
}
}
public static void copyCaretPosition(JTextComponent source, JTextComponent destination) {
try {
destination.setCaretPosition(source.getCaretPosition());
}
catch (Exception ignored) {
}
}
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());
}
}
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;
}
@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);
}
private void setText (JTextComponent comp, String text) {
comp.setText(text);
comp.setCaretPosition(comp.getText().length());
comp.moveCaretPosition(0);
}
protected void moveToNewOffset(JTextComponent textComponent, int offset) throws BadLocationException {
textComponent.setCaretPosition(offset);
}
/**
* 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);
}