javax.swing.text.JTextComponent#replaceSelection ( )源码实例Demo

下面列出了javax.swing.text.JTextComponent#replaceSelection ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: nextreports-designer   文件: SyntaxEditorKit.java
public void actionPerformed(ActionEvent event) {
    JTextComponent target = getTextComponent(event);
    Integer tabStop = (Integer) target.getDocument().getProperty(PlainDocument.tabSizeAttribute);
    String indent = SyntaxUtil.SPACES.substring(0, tabStop);
    if (target != null) {
        String[] lines = SyntaxUtil.getSelectedLines(target);
        int start = target.getSelectionStart();
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (line.startsWith(indent)) {
                sb.append(line.substring(indent.length()));
            } else if (line.startsWith("\t")) {
                sb.append(line.substring(1));
            } else {
                sb.append(line);
            }
            sb.append('\n');
        }
        target.replaceSelection(sb.toString());
        target.select(start, start + sb.length());
    }
}
 
源代码2 项目: visualvm   文件: JUnindentAction.java
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target);
        int pos = target.getCaretPosition();
        int start = sDoc.getParagraphElement(pos).getStartOffset();
        String line = ActionUtils.getLine(target);
        if (ActionUtils.isEmptyOrBlanks(line)) {
            try {
                sDoc.insertString(pos, "}", null);
                Token t = sDoc.getPairFor(sDoc.getTokenAt(pos));
                if (null != t) {
                    String pairLine = ActionUtils.getLineAt(target, t.start);
                    String indent = ActionUtils.getIndent(pairLine);
                    sDoc.replace(start, line.length() + 1, indent + "}", null);
                }
            } catch (BadLocationException ble) {
                target.replaceSelection("}");
            }
        } else {
            target.replaceSelection("}");
        }
    }
}
 
源代码3 项目: visualvm   文件: ToggleCommentsAction.java
/**
 * {@inheritDoc}
 * @param e 
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null && target.getDocument() instanceof SyntaxDocument) {
        String[] lines = ActionUtils.getSelectedLines(target);
        StringBuffer toggled = new StringBuffer();
        for (int i = 0; i < lines.length; i++) {
            Matcher m = lineCommentPattern.matcher(lines[i]);
            if (m.find()) {
                toggled.append(m.replaceFirst("$2"));
            } else {
                toggled.append(lineCommentStart);
                toggled.append(lines[i]);
            }
            toggled.append('\n');
        }
        target.replaceSelection(toggled.toString());
    }
}
 
源代码4 项目: visualvm   文件: UnindentAction.java
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    Integer tabStop = (Integer) target.getDocument().getProperty(PlainDocument.tabSizeAttribute);
    String indent = ActionUtils.SPACES.substring(0, tabStop);
    if (target != null) {
        String[] lines = ActionUtils.getSelectedLines(target);
        int start = target.getSelectionStart();
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (line.startsWith(indent)) {
                sb.append(line.substring(indent.length()));
            } else if (line.startsWith("\t")) {
                sb.append(line.substring(1));
            } else {
                sb.append(line);
            }
            sb.append('\n');
        }
        target.replaceSelection(sb.toString());
        target.select(start, start + sb.length());
    }
}
 
源代码5 项目: visualvm   文件: IndentAction.java
@Override
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        String selected = target.getSelectedText();
        if (selected == null) {
            PlainDocument pDoc = (PlainDocument) target.getDocument();
            Integer tabStop = (Integer) pDoc.getProperty(PlainDocument.tabSizeAttribute);
            int lineStart = pDoc.getParagraphElement(target.getCaretPosition()).getStartOffset();
            int column = target.getCaretPosition() - lineStart;
            int needed = tabStop - (column % tabStop);
            target.replaceSelection(ActionUtils.SPACES.substring(0, needed));
        } else {
            String[] lines = ActionUtils.getSelectedLines(target);
            int start = target.getSelectionStart();
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append('\t');
                sb.append(line);
                sb.append('\n');
            }
            target.replaceSelection(sb.toString());
            target.select(start, start + sb.length());
        }
    }
}
 
源代码6 项目: jpexs-decompiler   文件: PythonIndentAction.java
/**
 * {@inheritDoc}
 * @param e 
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target);
        int pos = target.getCaretPosition();
        int start = sDoc.getParagraphElement(pos).getStartOffset();
        String line = ActionUtils.getLine(target);
        String lineToPos = line.substring(0, pos - start);
        String prefix = ActionUtils.getIndent(line);
        int tabSize = ActionUtils.getTabSize(target);
        if (lineToPos.trim().endsWith(":")) {
            prefix += ActionUtils.SPACES.substring(0, tabSize);
        } else {
            String noComment = sDoc.getUncommentedText(start, pos); // skip EOL comments

            if (noComment.trim().endsWith(":")) {
                prefix += ActionUtils.SPACES.substring(0, tabSize);
            }
        }
        target.replaceSelection("\n" + prefix);
    }
}
 
源代码7 项目: jpexs-decompiler   文件: XmlTagCompleteAction.java
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sDoc,
        int dot, ActionEvent e) {
    Token tok = sDoc.getTokenAt(dot);
    while (tok != null && tok.type != TokenType.TYPE) {
        tok = sDoc.getPrevToken(tok);
    }
    if (tok == null) {
        target.replaceSelection(">");
    } else {
        CharSequence tag = tok.getText(sDoc);
        int savepos = target.getSelectionStart();
        target.replaceSelection("></" + tag.subSequence(1, tag.length()) + ">");
        target.setCaretPosition(savepos + 1);
    }
}
 
源代码8 项目: jpexs-decompiler   文件: JUnindentAction.java
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sDoc,
        int dot, ActionEvent e) {
    int pos = target.getCaretPosition();
    int start = sDoc.getParagraphElement(pos).getStartOffset();
    String line = ActionUtils.getLine(target);
    if (ActionUtils.isEmptyOrBlanks(line)) {
        try {
            sDoc.insertString(pos, "}", null);
            Token t = sDoc.getPairFor(sDoc.getTokenAt(pos));
            if (null != t) {
                String pairLine = ActionUtils.getLineAt(target, t.start);
                String indent = ActionUtils.getIndent(pairLine);
                sDoc.replace(start, line.length() + 1, indent + "}", null);
            }
        } catch (BadLocationException ble) {
            target.replaceSelection("}");
        }
    } else {
        target.replaceSelection("}");
    }
}
 
源代码9 项目: jpexs-decompiler   文件: ActionUtils.java
/**
 * Expand the string template and replaces the selection with the expansion
 * of the template.  The template String may contain any of the following
 * special tags.
 *
 * <li>{@code #{selection}} replaced with the selection, if any.  If there is
 * no selection, then the {@code #{selection}} tag will be removed.
 * <li>{@code #{p:AnyText}} will be replaced by {@code any text} and then
 * set the text selection to {@code AnyText}
 *
 * This methood does NOT perform any indentation and the template should
 * generally span one line only
 *
 * @param target
 * @param template
 */
public static void insertSimpleTemplate(JTextComponent target, String template) {
	String selected = target.getSelectedText();
	selected = (selected == null) ? "" : selected;
	StringBuffer sb = new StringBuffer(template.length());
	Matcher pm = PTAGS_PATTERN.matcher(template.replace(TEMPLATE_SELECTION, selected));
	int selStart = -1, selEnd = -1;
	int lineStart = 0;
	while (pm.find()) {
		selStart = pm.start() + lineStart;
		pm.appendReplacement(sb, pm.group(1));
		selEnd = sb.length();
	}
	pm.appendTail(sb);
	// String expanded = template.replace(TEMPLATE_SELECTION, selected);

	if (selStart >= 0) {
		selStart += target.getSelectionStart();
		selEnd += target.getSelectionStart();
	}
	target.replaceSelection(sb.toString());
	if (selStart >= 0) {
		// target.setCaretPosition(selStart);
		target.select(selStart, selEnd);
	}
}
 
源代码10 项目: jpexs-decompiler   文件: ToggleCommentsAction.java
/**
 * {@inheritDoc}
 * @param e 
 */
@Override
public void actionPerformed(JTextComponent target, SyntaxDocument sDoc,
        int dot, ActionEvent e) {
    if (lineCommentPattern == null) {
        lineCommentPattern = Pattern.compile("(^" + lineCommentStart + ")(.*)");
    }
    String[] lines = ActionUtils.getSelectedLines(target);
    int start = target.getSelectionStart();
    StringBuffer toggled = new StringBuffer();
    for (int i = 0; i < lines.length; i++) {
        Matcher m = lineCommentPattern.matcher(lines[i]);
        if (m.find()) {
            toggled.append(m.replaceFirst("$2"));
        } else {
            toggled.append(lineCommentStart);
            toggled.append(lines[i]);
        }
        toggled.append('\n');
    }
    target.replaceSelection(toggled.toString());
    target.select(start, start + toggled.length());
}
 
源代码11 项目: nextreports-designer   文件: SyntaxEditorKit.java
public void actionPerformed(ActionEvent event) {
    JTextComponent target = getTextComponent(event);
    if (target != null) {
        String line = SyntaxUtil.getLine(target);
        /**
         * Perform Smart Indentation:  pos must be on a line: this method will
         * use the previous lines indentation (number of spaces before any non-space
         * character or end of line) and return that as the prefix.
         */
        String indent = "";
        if (line != null && line.length() > 0) {
        	int i = 0;
        	while (i < line.length() && line.charAt(i) == ' ') {
        		i++;
        	}

        	indent = line.substring(0, i);
        }

        target.replaceSelection("\n" + indent);
    }
}
 
源代码12 项目: 3Dscript   文件: AnimationAutoCompletion.java
/**
 * Inserts a completion. Any time a code completion event occurs, the actual
 * text insertion happens through this method.
 *
 * @param c A completion to insert. This cannot be <code>null</code>.
 * @param typedParamListStartChar Whether the parameterized completion start
 *        character was typed (typically <code>'('</code>).
 */
@Override
protected void insertCompletion(Completion c,
		boolean typedParamListStartChar) {

	JTextComponent textComp = getTextComponent();
	String alreadyEntered = c.getAlreadyEntered(textComp);
	hidePopupWindow();
	Caret caret = textComp.getCaret();

	int dot = caret.getDot();
	int len = alreadyEntered.length();
	int start = dot - len;
	String replacement = getReplacementText(c, textComp.getDocument(),
			start, len);

	// Bene
	if(replacement != null && replacement.startsWith("(none)"))
		return;

	caret.setDot(start);
	caret.moveDot(dot);
	textComp.replaceSelection(replacement);

	if (isParameterAssistanceEnabled()
			&& (c instanceof ParameterizedCompletion)) {
		ParameterizedCompletion pc = (ParameterizedCompletion) c;
		startParameterizedCompletionAssistance(pc, typedParamListStartChar);
	}

}
 
源代码13 项目: nextreports-designer   文件: SyntaxEditorKit.java
public void actionPerformed(ActionEvent event) {
    JTextComponent target = getTextComponent(event);
    if (target != null) {
        String selected = target.getSelectedText();
        if (selected != null) {
            target.replaceSelection(left + selected + right);
        } else {
            target.replaceSelection(left + right);
        }
        target.setCaretPosition(target.getCaretPosition() - 1);
    }
}
 
源代码14 项目: visualvm   文件: JavaIndentAction.java
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);
        }
    }
}
 
源代码15 项目: visualvm   文件: PairAction.java
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);
    }
}
 
源代码16 项目: visualvm   文件: SmartIndent.java
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        String line = ActionUtils.getLine(target);
        target.replaceSelection("\n" + ActionUtils.getIndent(line));
    }
}
 
源代码17 项目: nextreports-designer   文件: SyntaxEditorKit.java
@Override
public void actionPerformed(ActionEvent event) {
    JTextComponent target = getTextComponent(event);
    if (target != null) {
        String selected = target.getSelectedText();
        if (selected == null) {
            PlainDocument pDoc = (PlainDocument) target.getDocument();
            Integer tabStop = (Integer) pDoc.getProperty(PlainDocument.tabSizeAttribute);
            // insert needed number of tabs:
            int lineStart = pDoc.getParagraphElement(target.getCaretPosition()).getStartOffset();
            // column 
            int column = target.getCaretPosition() - lineStart;
            int needed = tabStop - (column % tabStop);
            target.replaceSelection(SyntaxUtil.SPACES.substring(0, needed));
        } else {
            String[] lines = SyntaxUtil.getSelectedLines(target);
            int start = target.getSelectionStart();
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append('\t');
                sb.append(line);
                sb.append('\n');
            }
            target.replaceSelection(sb.toString());
            target.select(start, start + sb.length());
        }
    }
}
 
源代码18 项目: jpexs-decompiler   文件: DocumentSearchData.java
/**
 * Replace single occurrence of match with the replacement.
 * @param target
 * @param replacement
 */
public void doReplace(JTextComponent target, String replacement) {
	if (target.getSelectedText() != null) {
		target.replaceSelection(replacement == null ? "" : replacement);
		doFindNext(target);
	}
}
 
源代码19 项目: jpexs-decompiler   文件: ActionUtils.java
/**
 * Expand the string template and replaces the selection with the expansion
 * of the template.  The template String may contain any of the following
 * special tags.
 *
 * <li>{@code #{selection}} replaced with the selection, if any.  If there is
 * no selection, then the {@code #{selection}} tag will be removed.
 * <li>{@code #{p:any text}} will be replaced by {@code any text} and then
 * set selection to {@code any text}
 *
 * This method properly handles indentation as follows:
 * The indentation of the whole block will match the indentation of the caret
 * line, or the line with the beginning of the selection, if the selection is
 * in whole line, i.e.e one or more lines of selected text. {@see selectLines()}
 *
 * @param target JEditorCOmponent to be affected
 * @param templateLines template split as a String array of lines.
 *
 * @see insertLinesTemplate
 */
public static void insertLinesTemplate(JTextComponent target, String[] templateLines) {
	// get some stuff we'll need:
	String thisIndent = getIndent(getLineAt(target, target.getSelectionStart()));
	String[] selLines = getSelectedLines(target);
	int selStart = -1, selEnd = -1;
	StringBuffer sb = new StringBuffer();
	for (String tLine : templateLines) {
		int selNdx = tLine.indexOf("#{selection}");
		if (selNdx >= 0) {
			// for each of the selected lines:
			for (String selLine : selLines) {
				sb.append(tLine.subSequence(0, selNdx));
				sb.append(selLine);
				sb.append('\n');
			}
		} else {
			sb.append(thisIndent);
			// now check for any ptags
			Matcher pm = PTAGS_PATTERN.matcher(tLine);
			int lineStart = sb.length();
			while (pm.find()) {
				selStart = pm.start() + lineStart;
				pm.appendReplacement(sb, pm.group(1));
				selEnd = sb.length();
			}
			pm.appendTail(sb);
			sb.append('\n');
		}
	}
	int ofst = target.getSelectionStart();
	target.replaceSelection(sb.toString());
	if (selStart >= 0) {
		// target.setCaretPosition(selStart);
		target.select(ofst + selStart, ofst + selEnd);
	}
}
 
源代码20 项目: i18n-editor   文件: DeleteAction.java
@Override
public void actionPerformed(ActionEvent e) {
       JTextComponent component = getFocusedComponent();
       component.replaceSelection("");
   }