Java Swing How to - Select text in JTextArea








Question

We would like to know how to select text in JTextArea.

Answer

//w ww. j ava 2s .c  om
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Main {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        JTextArea ta = new JTextArea(5, 32);
        ta.setText("That's one small step for man...\nOne giant leap for mankind.");

        ta.setSelectionStart(10);

        ta.setSelectionEnd(20);
        
        f.getContentPane().add(ta);
        f.setSize(100, 100);
        f.setVisible(true);

    }
}