Java Program to replace the first 10 characters in JTextArea



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);
      frame.add(textArea);
      frame.setSize(550,300);
      frame.setLayout(new GridLayout(2, 2));
      frame.setVisible(true);
   }
   public static void main(String args[]) {
      new SwingDemo ();
   }
}

Output


Advertisements