Using the Selection of a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Using the Selection of a JTextComponent

Demo Code

import java.awt.Color;

import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] argv) {
    JTextComponent c = new JTextArea();

    // Get text inside selection
    c.getSelectedText();/*from   ww  w.  j a  va 2 s  .c  o m*/

    // Replace selected text
    c.replaceSelection("replacement text");

    // Set the start of the selection; ignored if new start is < end
    c.setSelectionStart(10);

    // Set the end of the selection; ignored if new end is > start
    c.setSelectionEnd(20);

    // Better way to set the selection
    c.select(10, 20);

    // Set the color of text inside the selection
    c.setSelectedTextColor(Color.red);

    // Set the color behind the selected text
    c.setSelectionColor(Color.green);
  }

}

Related Tutorials