How to Insert a Text in a Specified Position of JTextArea Component in Java GU

This is a continuation of my other tutorials entitled JTextArea Component in Java GUI and Set Font and Color to Text of JTextArea Component in Java GUI. But in this tutorial, i will teach you how to insert a text in a specified position of JTextArea component using Java GUI. 1. First and foremost, Open JCreator or NetBeans and make a java program with a file name of jTextArea.java. When you click the link above, copy first all the code there.
  1.     import java.awt.*;
  2.     import javax.swing.*;
  3.      
  4.     public class jTextArea extends JFrame {
  5.      
  6.     JTextArea txtArea = new JTextArea(5,18);
  7.      
  8.     public jTextArea() {
  9.      
  10.     txtArea.setText("Encode more text to see scrollbars");
  11.     JScrollPane scrollingArea = new JScrollPane(txtArea);
  12.      
  13.     JPanel content = new JPanel();
  14.     content.setLayout(new BorderLayout());
  15.     content.add(scrollingArea, BorderLayout.CENTER);
  16.      
  17.     this.setContentPane(content);
  18.     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  19.     this.pack();
  20.     }
  21.      
  22.     public static void main(String[] args) {
  23.     JFrame txtArea = new jTextArea();
  24.     txtArea.setTitle("JTextArea Component");
  25.     txtArea.setVisible(true);
  26.     txtArea.setSize(250,140);
  27.     txtArea.setLocation(300,300);
  28.     }
  29.     }
2. Now, insert this code after the JScrollPane scrollingArea = new JScrollPane(txtArea);. This code will insert a text in your desired position of JTextArea component.
  1.         txtArea.insert("Sourcecodester ", 0);
  2.         txtArea.insert(" best ", 27);
The txtArea is our variable for JTextArea component that we used the insert method here. This insert method here allows to insert a text at the specified position. Meaning insert(String text,int position) is the syntax. Here, i used the word "Sourcecodester" at the position 0. This 0 means will be placed before the start of "Encode". Take note that you can also change the word i have inserted. I also used again the insert method with the word "best" in the 27th position which means the word will be place after the word "more". Output: output Hope this helps :) Best Regards, Engr. Lyndon R. Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment