Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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

Advertisements