Java Program to replace the first 10 characters in JTextArea

Java 8Object Oriented ProgrammingProgramming

To replace the first 10 character in text area, use the replaceRange() method in Java and replace the old text with the new text.

Let’s say the following is oude demo text set with JTextArea −

JTextArea textArea = new JTextArea("This is a text displayed for our example. We have replaced some of the text.");

Now, replace the characters in a range −

int begn = 0;
int end = 10;
// replace
textArea.replaceRange("Replaced! ", begn, end);

The following is an example to replace the first 10 charactrers in 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 replaced some of the text.");
int begn = 0;
int end = 10;
// replace
textArea.replaceRange("Replaced! ", begn, end);
}