Example usage for javax.swing.text PlainDocument getText

List of usage examples for javax.swing.text PlainDocument getText

Introduction

In this page you can find the example usage for javax.swing.text PlainDocument getText.

Prototype

public String getText(int offset, int length) throws BadLocationException 

Source Link

Document

Gets a sequence of text from the document.

Usage

From source file:ro.nextreports.designer.ui.sqleditor.syntax.SyntaxUtil.java

/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * //from  w  w w.  j a  v  a 2s .c  o m
 * Note that the strings returned will not contain the terminating line feeds.
 * 
 * The text component will then have the full lines set as selection.
 * 
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument document = (PlainDocument) target.getDocument();
        int start = document.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = document.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // 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
            end = document.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = document.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException e) {
        LOG.error(e.getMessage(), e);
        lines = EMPTY_STRING_ARRAY;
    }

    return lines;
}

From source file:ro.nextreports.designer.ui.sqleditor.syntax.SyntaxUtil.java

/**
 * Return the line of text at the given position. The returned value may
 * be null. It will not contain the trailing new-line character.
 * /*from   ww  w.  j  av  a  2  s. c o m*/
 * @param doc
 * @param pos
 * @return
 */
public static String getLineAt(PlainDocument doc, int pos) {
    String line = null;
    int start = doc.getParagraphElement(pos).getStartOffset();
    int end = doc.getParagraphElement(pos).getEndOffset();
    try {
        line = doc.getText(start, end - start);
        if (line != null && line.endsWith("\n")) {
            line = line.substring(0, line.length() - 1);
        }
    } catch (BadLocationException e) {
        LOG.error(e.getMessage(), e);
    }

    return line;
}