Delete the first 10 characters from JTextArea in Java



Let’s say the following is our JTextArea with default text −

JTextArea textArea = new JTextArea("The text added here is just for demo. "    + "\nThis demonstrates the usage of JTextArea in Java. In this example we have"    + "deleted some text.");

Now to remove the first 10 characters, use replaceRange() method and set null from one end to another i.e. deleting characters in a range. The replaceRaneg() method Replaces text from the indicated start to end position with the new text specified i.e.e here null will replace the first 10 characters −

int start = 0; int end = 10; textArea.replaceRange(null, start, end);

The following is an example to delete the first 10 characters from JTextArea −

Example

package my; import java.awt.GridLayout; import javax.swing.*; public class SwingDemo {    SwingDemo() {       JFrame frame = new JFrame("Demo");       JTextArea textArea = new JTextArea("The text added here is just for demo. " + "\nThis demonstrates the usage of JTextArea in Java. In this example we have" + "deleted some text.");       int start = 0;       int end = 10;       textArea.replaceRange(null, start, 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 ();    } }

The output is as follows. We have deleted first 10 characters here −

Output

Updated on: 2019-07-30T22:30:26+05:30

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements