Example usage for javax.swing.text Document getText

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

Introduction

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

Prototype

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

Source Link

Document

Fetches the text contained within the given portion of the document.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JTextArea comp = new JTextArea();
    String actionName = "Lowercase";

    JFrame f = new JFrame();
    f.add(new JScrollPane(comp));
    f.setSize(300, 300);//from   ww  w.ja v a  2s  . c  o  m
    f.setVisible(true);
    comp.getInputMap().put(KeyStroke.getKeyStroke("F2"), actionName);

    comp.getActionMap().put(actionName, new TextAction(actionName) {
        public void actionPerformed(ActionEvent evt) {
            JTextComponent comp = getTextComponent(evt);

            if (comp.getSelectionStart() == comp.getSelectionEnd()) {
                if (comp.getCaretPosition() < comp.getDocument().getLength()) {
                    try {
                        int pos = comp.getCaretPosition();
                        Document doc = comp.getDocument();
                        String str = doc.getText(pos, 1).toLowerCase();

                        doc.remove(pos, 1);
                        doc.insertString(pos, str, null);
                        comp.moveCaretPosition(pos + 1);
                    } catch (Exception e) {
                        System.out.println();
                    }
                }
            } else {
                int s = comp.getSelectionStart();
                int e = comp.getSelectionEnd();

                comp.replaceSelection(comp.getSelectedText().toLowerCase());
                comp.select(s, e);
            }
        }
    });
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);
    frame.add(new JTextField(), BorderLayout.SOUTH);

    DocumentListener documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);//w w  w . java 2  s.  com
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            String typeString = null;
            if (type.equals(DocumentEvent.EventType.CHANGE)) {
                typeString = "Change";
            } else if (type.equals(DocumentEvent.EventType.INSERT)) {
                typeString = "Insert";
            } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
                typeString = "Remove";
            }
            System.out.print("Type  :   " + typeString + " / ");
            Document source = documentEvent.getDocument();
            int length = source.getLength();
            try {
                System.out.println("Contents: " + source.getText(0, length));
            } catch (BadLocationException badLocationException) {
                System.out.println("Contents: Unknown");
            }
        }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250, 100);
    frame.setVisible(true);
}

From source file:Main.java

public static String getDocumentText(final Document document) {
    try {/*from  www  .  j a  v  a2 s.  c o m*/
        return document.getText(0, document.getLength());
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static void highlight(JTextComponent textComp, String pattern) throws Exception {
    removeHighlights(textComp);/*from w ww  . j ava  2 s .co  m*/

    Highlighter hilite = textComp.getHighlighter();
    Document doc = textComp.getDocument();
    String text = doc.getText(0, doc.getLength());
    int pos = 0;

    while ((pos = text.indexOf(pattern, pos)) >= 0) {
        hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
        pos += pattern.length();
    }

}

From source file:Main.java

private static int getTagEnd(Document doc, int p) {
    int elementEnd = 0;

    if (p > 0) {
        try {//from w w  w .j  ava  2s  .c  o  m
            int index = 0;

            String s = doc.getText(0, p);
            int commentStart = s.lastIndexOf("<!--");
            int commentEnd = s.lastIndexOf("-->");

            if (commentStart > 0 && commentStart > commentEnd) {
                index = s.lastIndexOf(">", commentStart);
            } else {
                index = s.lastIndexOf(">");
            }

            if (index != -1) {
                elementEnd = index;
            }
        } catch (BadLocationException bl) {
        }
    }

    return elementEnd;
}

From source file:com.mirth.connect.server.userutil.FileUtil.java

/**
 * Converts an RTF into plain text using the Swing RTFEditorKit.
 * /*  w w w .  jav a 2  s  .c  o m*/
 * @param message
 *            The RTF message to convert.
 * @param replaceLinebreaksWith
 *            If not null, any line breaks in the converted message will be replaced with this
 *            string.
 * @return The converted plain text message.
 * @throws IOException
 * @throws BadLocationException
 */
public static String rtfToPlainText(String message, String replaceLinebreaksWith)
        throws IOException, BadLocationException {

    String convertedPlainText;

    // Reading the RTF content string
    Reader in = new StringReader(message);

    // creating a default blank styled document
    DefaultStyledDocument styledDoc = new DefaultStyledDocument();

    // Creating a RTF Editor kit
    RTFEditorKit rtfKit = new RTFEditorKit();

    // Populating the contents in the blank styled document
    rtfKit.read(in, styledDoc, 0);

    // Getting the root document
    Document doc = styledDoc.getDefaultRootElement().getDocument();

    convertedPlainText = doc.getText(0, doc.getLength());
    if (replaceLinebreaksWith != null) {
        convertedPlainText = convertedPlainText.replaceAll("\\n", replaceLinebreaksWith);
    }

    return convertedPlainText;
}

From source file:com.mirth.connect.server.util.FileUtil.java

public static String rtfToPlainText(String message, String replaceLinebreaksWith)
        throws IOException, BadLocationException {

    String convertedPlainText;//from w  w  w . j a  v a  2s . c  om

    // Reading the RTF content string
    Reader in = new StringReader(message);

    // creating a default blank styled document
    DefaultStyledDocument styledDoc = new DefaultStyledDocument();

    // Creating a RTF Editor kit
    RTFEditorKit rtfKit = new RTFEditorKit();

    // Populating the contents in the blank styled document
    rtfKit.read(in, styledDoc, 0);

    // Getting the root document
    Document doc = styledDoc.getDefaultRootElement().getDocument();

    convertedPlainText = doc.getText(0, doc.getLength());
    if (replaceLinebreaksWith != null) {
        convertedPlainText = convertedPlainText.replaceAll("\\n", replaceLinebreaksWith);
    }

    return convertedPlainText;
}

From source file:HTML.java

/**
 * Utility method to convert HTML to text.
 * @param html The string containing HTML.
 * @return a String containing the derived text .
 *///from  w  ww  .  j  a  va  2s. co  m
public static final String html2text(String html) {
    EditorKit kit = new HTMLEditorKit();
    Document doc = kit.createDefaultDocument();
    doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
    try {
        Reader reader = new StringReader(html);
        kit.read(reader, doc, 0);
        return doc.getText(0, doc.getLength());
    } catch (Exception e) {

        return "";
    }
}

From source file:TextUtilities.java

/**
 * Returns the offset of the bracket matching the one at the specified offset
 * of the document, or -1 if the bracket is unmatched (or if the character is
 * not a bracket).//from  w w  w  .j av a 2 s .co  m
 * 
 * @param doc
 *           The document
 * @param offset
 *           The offset
 * @exception BadLocationException
 *               If an out-of-bounds access was attempted on the document
 *               text
 */
public static int findMatchingBracket(Document doc, int offset) throws BadLocationException {
    if (doc.getLength() == 0)
        return -1;
    char c = doc.getText(offset, 1).charAt(0);
    char cprime; // c` - corresponding character
    boolean direction; // true = back, false = forward

    switch (c) {
    case '(':
        cprime = ')';
        direction = false;
        break;
    case ')':
        cprime = '(';
        direction = true;
        break;
    case '[':
        cprime = ']';
        direction = false;
        break;
    case ']':
        cprime = '[';
        direction = true;
        break;
    case '{':
        cprime = '}';
        direction = false;
        break;
    case '}':
        cprime = '{';
        direction = true;
        break;
    default:
        return -1;
    }

    int count;

    // How to merge these two cases is left as an exercise
    // for the reader.

    // Go back or forward
    if (direction) {
        // Count is 1 initially because we have already
        // `found' one closing bracket
        count = 1;

        // Get text[0,offset-1];
        String text = doc.getText(0, offset);

        // Scan backwards
        for (int i = offset - 1; i >= 0; i--) {
            // If text[i] == c, we have found another
            // closing bracket, therefore we will need
            // two opening brackets to complete the
            // match.
            char x = text.charAt(i);
            if (x == c)
                count++;

            // If text[i] == cprime, we have found a
            // opening bracket, so we return i if
            // --count == 0
            else if (x == cprime) {
                if (--count == 0)
                    return i;
            }
        }
    } else {
        // Count is 1 initially because we have already
        // `found' one opening bracket
        count = 1;

        // So we don't have to + 1 in every loop
        offset++;

        // Number of characters to check
        int len = doc.getLength() - offset;

        // Get text[offset+1,len];
        String text = doc.getText(offset, len);

        // Scan forwards
        for (int i = 0; i < len; i++) {
            // If text[i] == c, we have found another
            // opening bracket, therefore we will need
            // two closing brackets to complete the
            // match.
            char x = text.charAt(i);

            if (x == c)
                count++;

            // If text[i] == cprime, we have found an
            // closing bracket, so we return i if
            // --count == 0
            else if (x == cprime) {
                if (--count == 0)
                    return i + offset;
            }
        }
    }

    // Nothing found
    return -1;
}

From source file:TextFieldViews.java

public static void displayView(View view, int indent, Document doc, PrintStream out) {
    String name = view.getClass().getName();
    for (int i = 0; i < indent; i++) {
        out.print("\t");
    }//from  w  w w  .j  av  a  2s .  co m

    int start = view.getStartOffset();
    int end = view.getEndOffset();
    out.println(name + "; offsets [" + start + ", " + end + "]");
    int viewCount = view.getViewCount();
    if (viewCount == 0) {
        int length = Math.min(32, end - start);
        try {
            String txt = doc.getText(start, length);
            for (int i = 0; i < indent + 1; i++) {
                out.print("\t");
            }
            out.println("[" + txt + "]");
        } catch (BadLocationException e) {
        }
    } else {
        for (int i = 0; i < viewCount; i++) {
            displayView(view.getView(i), indent + 1, doc, out);
        }
    }
}