Code example for JTextComponent

Methods: getSelectedTextgetSelectionEndgetSelectionStartreplaceSelectionselect

0
	 * 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);
		} 
	} 
 
	/** 
	 * FInd the previous match 
	 * @param target 
	 * @return 
	 */ 
	public boolean doFindPrev(JTextComponent target) {
		if (getPattern() == null) { 
			return false; 
		} 
		SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target);
		if (sDoc == null) {
			return false; 
		} 
		int dot = target.getSelectionStart();
		Matcher matcher = sDoc.getMatcher(getPattern());
		if (matcher == null) {
			return false; 
		} 
		// we have no way of jumping to last match, so we need to 
		// go throw all matches, and stop when we reach current pos 
		int start = -1;
		int end = -1;
		while (matcher.find()) {
			if (matcher.end() >= dot) {
				break; 
			} 
			start = matcher.start();
			end = matcher.end();
		} 
		if (end > 0) {
			target.select(start, end);
			return true; 
		} else { 
			return false; 
		} 
	} 
 
	/** 
	 * Perform a FindNext operation on the given text component.  Position 
	 * the caret at the start of the next found pattern. 
	 * @param target 
	 * @return true if pattern is found, false otherwise 
	 */ 
	public boolean doFindNext(JTextComponent target) {
		if (getPattern() == null) { 
			return false; 
		} 
		SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target);
		if (sDoc == null) {
			return false; 
		} 
		int start = target.getSelectionEnd();
		if (target.getSelectionEnd() == target.getSelectionStart()) {
			// we must advance the position by one, otherwise we will find 
			// the same text again 
			start++;
		} 
		if (start >= sDoc.getLength()) {
			start = sDoc.getLength();
		} 
		Matcher matcher = sDoc.getMatcher(getPattern(), start);
		if (matcher != null && matcher.find()) {
			// since we used an offset in the matcher, the matcher location 
			// MUST be offset by that location 
			target.select(matcher.start() + start, matcher.end() + start);
			return true; 
		} else { 
			if (isWrap()) { 
				matcher = sDoc.getMatcher(getPattern());
				if (matcher != null && matcher.find()) {
					target.select(matcher.start(), matcher.end());
					return true; 
				} else { 
					return false; 
				} 
			} else { 
Experience pair programming with AI  Get Codota for Java