Java JTextComponent Select selectLines(JTextComponent target)

Here you can find the source of selectLines(JTextComponent target)

Description

If the selection is multi lined, then the full lines are selected, otherwise, nothing is done.

License

Apache License

Parameter

Parameter Description
target a parameter

Return

true if the selection is multi-line, or a whole line

Declaration

public static boolean selectLines(JTextComponent target) 

Method Source Code

//package com.java2s;
/*/*ww  w .ja va 2  s.  co  m*/
 * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License 
 *       at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.  
 */

import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

public class Main {
    /**
     * If the selection is multi lined, then the full lines are selected,
     * otherwise, nothing is done.
     * @param target
     * @return true if the selection is multi-line, or a whole line
     */
    public static boolean selectLines(JTextComponent target) {
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            return false;
        }
        PlainDocument pDoc = (PlainDocument) target.getDocument();
        Element es = pDoc.getParagraphElement(target.getSelectionStart());
        // if more than one line is selected, we need to subtract one from the end
        // so that we do not select the line with the caret and no selection in it
        Element ee = pDoc.getParagraphElement(target.getSelectionEnd() - 1);
        if (es.equals(ee) && ee.getEndOffset() != target.getSelectionEnd()) {
            return false;
        }
        int start = es.getStartOffset();
        int end = ee.getEndOffset();
        target.select(start, end - 1);
        return true;
    }
}

Related

  1. selectAll(JTextComponent textComponent)
  2. selectAllOnFocus(JTextComponent textComponent)
  3. selectAndRequestFocus(JTextComponent editor)
  4. selectFirstArg(String strText, int initialSelectionStart, JTextComponent editor)
  5. selectionToUpperCase(JTextComponent textPane)
  6. toggleSelectionUpperCase(JTextComponent textPane)
  7. useSelectedTextColor(Highlighter.Highlight h, JTextComponent c)