Jeris
Jeris

Reputation: 2483

Inserting text in JTextArea

i am developing a simple application in Java and i wanted to know if there is any way i can insert additional text(somewhere in the middle of a sentence) inside a textarea , which is not empty, at a position where the cursor is placed on the click of some component. Can someone please direct me how to go about getting it done

Upvotes: 3

Views: 24352

Answers (3)

jefflunt
jefflunt

Reputation: 33954

If this is a JTextArea component you can use the .append method to add text to the end of the text area, or the .insert method to insert the new text at a specific position.

If you need to insert the text at the current caret position use the .getCaretPosition method

Upvotes: 11

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Check out: JTextComponent.getCaretPosition().

The method getCaretPosition() is inherited by JTextArea, you can use it to get the cursor position. Then you can use JTextArea.insert(String str, int pos) to insert text at that position.

Sample:

JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTextArea jta = new JTextArea("Hello world\nHello world\nHello world");
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int pos = jta.getCaretPosition(); //get the cursor position
        jta.insert("Some more", pos); //insert your text
    }            
});
frame.add(jta, BorderLayout.CENTER);
frame.add(btn, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
frame.pack();
frame.setVisible(true);

Upvotes: 5

camickr
camickr

Reputation: 324197

textArea.replaceSelection(text);

From the API:

Replaces the currently selected content with new content represented by the given string. If there is no selection this amounts to an insert of the given text

Upvotes: 6

Related Questions