Can we select only some of the text in JTextArea?


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 −

Example

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 −

Output

Updated on: 30-Jul-2019

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements