Java Code Examples for javax.swing.JTextArea#setSelectionStart()

The following examples show how to use javax.swing.JTextArea#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: MainView.java    From HiJson with Apache License 2.0 4 votes vote down vote up
/**
 * 文本内容查找定位
 * @param key 要查找的字符串
 * @param ignoreCase 是否区分大小写
 * @param down  查找方向(向上false,向下true)
 * @param isFirst 是否从开头开始查找
 * @return
 */
public boolean startSegmentFindOrReplaceOperation(JTextArea textArea, String key, boolean ignoreCase, boolean down,boolean isFirst) {
    int length = key.length();
    Document doc = textArea.getDocument();
    int offset = textArea.getCaretPosition();
    int charsLeft = doc.getLength() - offset;
    if(charsLeft <=0 ){
        offset = 0;
        charsLeft = doc.getLength() - offset;
    }
    if (!down) {
        offset -= length;
        offset--;
        charsLeft = offset;
    }
    if(isFirst){
        offset = 0;
        charsLeft = doc.getLength() - offset;
    }
    Segment text = new Segment();
    text.setPartialReturn(true);
    try {
        while (charsLeft > 0) {
            doc.getText(offset, length, text);
            if ((ignoreCase == true && text.toString().equalsIgnoreCase(key))
                    || (ignoreCase == false && text.toString().equals(key))) {
                textArea.requestFocus();////焦点,才能能看到效果
                textArea.setSelectionStart(offset);
                textArea.setSelectionEnd(offset + length);
                return true;
            }
            charsLeft--;
            if (down) {
                offset++;
            } else {
                offset--;
            }

        }
    } catch (Exception e) {

    }
    return false;
}