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

The following examples show how to use javax.swing.text.JTextComponent#setSelectionStart() . 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: TextComponentUpdater.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void setTextFieldValue(String value, String projectValue, JTextComponent field) {
        if (value != null) {
            field.setText(value);
            component.setToolTipText(null);
            inherited = false;
            label.setFont(label.getFont().deriveFont(Font.BOLD));
        } else if (projectValue != null) {
            field.setText(projectValue);
            field.setSelectionEnd(projectValue.length());
            field.setSelectionStart(0);
//            field.setBackground(INHERITED);
            label.setFont(label.getFont().deriveFont(Font.PLAIN));
            component.setToolTipText(MSG_Value_Inherited());
            inherited = true;
        } else {
            field.setText("");//NOI18N
            component.setToolTipText(null);
            inherited = false;
            label.setFont(label.getFont().deriveFont(Font.BOLD));
        }
    }
 
Example 2
Source File: ActionMappings.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void replacePattern(String pattern, JTextComponent area, String replace, boolean select) {
    String props = area.getText();
    Matcher match = Pattern.compile(pattern, Pattern.DOTALL).matcher(props);
    if (match.matches()) {
        int begin = props.indexOf(TestChecker.PROP_SKIP_TEST);
        props = props.replace(TestChecker.PROP_SKIP_TEST + match.group(1), replace); //NOI18N
        area.setText(props);
        if (select) {
            area.setSelectionStart(begin);
            area.setSelectionEnd(begin + replace.length());
            area.requestFocusInWindow();
        }
    } else {
        String sep = "\n";//NOI18N
        if (props.endsWith("\n") || props.trim().length() == 0) {//NOI18N
            sep = "";//NOI18N
        }
        props = props + sep + replace; //NOI18N
        area.setText(props);
        if (select) {
            area.setSelectionStart(props.length() - replace.length());
            area.setSelectionEnd(props.length());
            area.requestFocusInWindow();
        }
    }

}
 
Example 3
Source File: ComboInplaceEditor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void prepareEditor() {
    Component c = getEditor().getEditorComponent();

    if (c instanceof JTextComponent) {
        JTextComponent jtc = (JTextComponent) c;
        String s = jtc.getText();

        if ((s != null) && (s.length() > 0)) {
            jtc.setSelectionStart(0);
            jtc.setSelectionEnd(s.length());
        }

        if (tableUI) {
            jtc.setBackground(getBackground());
        } else {
            jtc.setBackground(PropUtils.getTextFieldBackground());
        }
        if( tableUI )
            jtc.requestFocus();
    }

    if (getLayout() != null) {
        getLayout().layoutContainer(this);
    }

    repaint();
}
 
Example 4
Source File: TextHelpers.java    From binnavi with Apache License 2.0 5 votes vote down vote up
public static void insert(final JTextComponent component, final String string) {
  final int start = component.getSelectionStart();

  insert(component, start, string);

  component.setSelectionStart(start + string.length());
  component.setSelectionEnd(start + string.length());
}
 
Example 5
Source File: FileUtils.java    From weblaf with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets file name as text and selects its name part in any text component.
 *
 * @param editor text editor to process
 * @param file   file to process
 */
public static void displayFileName ( @NotNull final JTextComponent editor, @NotNull final File file )
{
    final String name = file.getName ();
    editor.setText ( name );
    editor.setSelectionStart ( 0 );
    editor.setSelectionEnd ( file.isDirectory () ? name.length () : FileUtils.getFileNamePart ( name ).length () );
}
 
Example 6
Source File: Preferences.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
void apply(JTextComponent cmp) {
     if(!applied && cmp.getDocument().getLength() >= len) {
if(dot == mark) {
  cmp.setCaretPosition(dot);
} else {
  cmp.setSelectionStart(mark);
  cmp.setSelectionEnd(dot);
  cmp.getCaret().setSelectionVisible(true);
}
if(focus) cmp.requestFocus();
applied = true;
     }
   }
 
Example 7
Source File: CustomCodeView.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    if (ignoreComboAction)
        return; // not invoked by user, ignore

    GuardedBlock gBlock = codeData.getGuardedBlock(category, blockIndex);
    GuardBlockInfo gInfo = getGuardInfos(category)[blockIndex];
    int[] blockBounds = getGuardBlockBounds(category, blockIndex);
    int startOffset = blockBounds[0];
    int endOffset = blockBounds[1];
    int gHead = gBlock.getHeaderLength();
    int gFoot = gBlock.getFooterLength();
    JTextComponent editor = getEditor(category);
    StyledDocument doc = (StyledDocument) editor.getDocument();

    changed = true;

    JComboBox combo = (JComboBox) e.getSource();
    try {
        docListener.setActive(false);
        if (combo.getSelectedIndex() == 1) { // changing from default to custom
            NbDocument.unmarkGuarded(doc, startOffset, endOffset - startOffset);
            // keep last '\n' so we don't destroy next editable block's position
            doc.remove(startOffset, endOffset - startOffset - 1);
            // insert the custom code into the document
            String customCode = gBlock.getCustomCode();
            int customLength = customCode.length();
            if (gInfo.customizedCode != null) { // already was edited before
                customCode = customCode.substring(0, gHead)
                             + gInfo.customizedCode
                             + customCode.substring(customLength - gFoot);
                customLength = customCode.length();
            }
            if (customCode.endsWith("\n")) // NOI18N
                customCode = customCode.substring(0, customLength-1);
            doc.insertString(startOffset, customCode, null);
            gInfo.customized = true;
            // make guarded "header" and "footer", select the text in between
            NbDocument.markGuarded(doc, startOffset, gHead);
            NbDocument.markGuarded(doc, startOffset + customLength - gFoot, gFoot);
            editor.setSelectionStart(startOffset + gHead);
            editor.setSelectionEnd(startOffset + customLength - gFoot);
            editor.requestFocus();
            combo.setToolTipText(gBlock.getCustomEntry().getToolTipText());
        }
        else { // changing from custom to default
            // remember the customized code
            gInfo.customizedCode = doc.getText(startOffset + gHead,
                                               endOffset - gFoot - gHead - startOffset);
            NbDocument.unmarkGuarded(doc, endOffset - gFoot, gFoot);
            NbDocument.unmarkGuarded(doc, startOffset, gHead);
            // keep last '\n' so we don't destroy next editable block's position
            doc.remove(startOffset, endOffset - startOffset - 1);
            String defaultCode = gBlock.getDefaultCode();
            if (defaultCode.endsWith("\n")) // NOI18N
                defaultCode = defaultCode.substring(0, defaultCode.length()-1);
            doc.insertString(startOffset, defaultCode, null);
            gInfo.customized = false;
            // make the whole text guarded, cancel selection
            NbDocument.markGuarded(doc, startOffset, defaultCode.length()+1); // including '\n'
            if (editor.getSelectionStart() >= startOffset && editor.getSelectionEnd() <= endOffset)
                editor.setCaretPosition(startOffset);
            combo.setToolTipText(NbBundle.getMessage(CustomCodeData.class, "CTL_GuardCombo_Default_Hint")); // NOI18N
        }
        // we must create a new Position - current was moved away by inserting new string on it
        gInfo.position = NbDocument.createPosition(doc, startOffset, Position.Bias.Forward);

        docListener.setActive(true);
    }
    catch (BadLocationException ex) { // should not happen
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
    }
}
 
Example 8
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void comment(JTextComponent target, BaseDocument doc, CommentHandler commentHandler, int[] comments, int from, int to, boolean lineSelection) throws BadLocationException {
//        System.out.println("comment");

        int diff = 0;
        String startDelim = commentHandler.getCommentStartDelimiter();
        String endDelim = commentHandler.getCommentEndDelimiter();

        //put the comment start
        boolean startInComment = false;
        
        if (comments.length > 0) {
            int cStart = comments[0];
            int cEnd = comments[1];
            
            if (cStart <= from && cEnd > from) {
                // the to-be-commented area starts in this comment
                startInComment = true;
            }
        }
        if (!startInComment) {
            // insert start comment mark
            diff += insert(doc, from, startDelim);
        }

        for (int i = 0; i < comments.length; i += 2) {
            int commentStart = comments[i];
            int commentEnd = comments[i + 1];
            if (commentStart >= from) {
                diff += remove(doc, commentStart + diff, startDelim.length());
            }

            if (commentEnd <= to) {
                diff += remove(doc, commentEnd + diff - endDelim.length(), endDelim.length());
            }

        }

        //add closing comment if the last comment doesn't contain the 'to' offset
        if (comments.length == 0 || comments[comments.length - 1] <= to) {
            diff += insert(doc, to + diff, endDelim);
        }

        if (!lineSelection) {
            //update the selection range, we always add the starting delimiter out of the selection
            target.setSelectionStart(from);
            target.setSelectionEnd(to + diff);
        }

    }
 
Example 9
Source File: SwingSearch.java    From pumpernickel with MIT License 4 votes vote down vote up
private static boolean find2(JTextComponent textComponent,
		String searchPhrase, boolean forward, boolean matchCase) {
	if (textComponent == null)
		throw new NullPointerException(
				"No text component was provided to search.");
	if (searchPhrase == null)
		throw new NullPointerException(
				"No search phrase was provided to search for.");

	if (searchPhrase.length() == 0)
		return false;

	if (matchCase == false)
		searchPhrase = searchPhrase.toUpperCase();

	int[] selection = new int[2];
	int startingIndex;
	if (forward) {
		startingIndex = Math.max(textComponent.getSelectionStart(),
				textComponent.getSelectionEnd());
	} else {
		startingIndex = Math.min(textComponent.getSelectionStart(),
				textComponent.getSelectionEnd());
	}
	int endIndex = forward ? textComponent.getDocument().getLength() : 0;
	if (find(textComponent, searchPhrase, forward, matchCase, true,
			startingIndex, endIndex, selection)) {
		int prevStart = Math.min(textComponent.getSelectionStart(),
				textComponent.getSelectionEnd());
		int prevEnd = Math.max(textComponent.getSelectionStart(),
				textComponent.getSelectionEnd());

		// if the selection doesn't change, do nothing.
		if (prevStart == selection[0] && prevEnd == selection[1])
			return false;

		textComponent.setSelectionStart(selection[0]);
		textComponent.setSelectionEnd(selection[1]);
		highlight(textComponent, selection[0], selection[1]);
		return true;
	}
	return false;
}