Yes, we can do that using built-in methods of JTextArea components. Let’say the following is our JTextArea −
JTextArea textArea = new JTextArea("This is a text displayed for our example. We have selected some of the text.");
Now, use the methods setSelectionStart() and setSelectionEnd() to select some text in a range −
textArea.setSelectionStart(5); textArea.setSelectionEnd(20);
The following is an example to select some of the text in a JTextArea −
package my; import java.awt.GridLayout; import javax.swing.*; public class SwingDemo { SwingDemo() { JFrame frame = new JFrame("Demo"); JTextArea textArea = new JTextArea("This is a text displayed for our example. We have selected some of the text."); textArea.setSelectionStart(5); textArea.setSelectionEnd(20); frame.add(textArea); frame.setSize(550,300); frame.setLayout(new GridLayout(2, 2)); frame.setVisible(true); } public static void main(String args[]) { new SwingDemo (); } }
This will produce the following output displaying selected text in a range −