user112862
user112862

Reputation: 35

How to change the text of selected text in Java?

I want to change the text of selected text in JTextArea.

For example when i press button i want the selected text to be change (Original Text Selected - I want to replace like this when i press the button : Replace:Original Text Selected) this is what i am trying to do in my code,

String replacement = "Replace:" + messageBodyText.getSelectedText() ";

but i have no idea how to change only selected text i am trying to do something but i am changing entire text of JTextArea Hope you understood my question ?

Thanks to Hovercraft Full Of Eels he solved my problem this is my code for other people who are facing the same problem :

int start = messageBodyText.getSelectionStart();
            int end = messageBodyText.getSelectionEnd();

            StringBuilder strBuilder = new StringBuilder(messageBodyText.getText());
            strBuilder.replace(start, end, "Replace:" + messageBodyText.getSelectedText() + ".");
            messageBodyText.setText(strBuilder.toString());

Upvotes: 3

Views: 4100

Answers (2)

camickr
camickr

Reputation: 324098

textComponent.replaceSelection(newText);

Upvotes: 6

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

JTextComponent (and thus JTextArea) has getSelectionStart() and getSelectionEnd() methods that will help you. Get your text from the JTextArea or its Document, and using these int values you can change your text and replace it into the text component.

For example,

int start = myTextField.getSelectionStart();
int end = myTextField.getSelectionEnd();
StringBuilder strBuilder = new StringBuilder(myTextField.getText());
strBuilder.replace(start, end, newText);
myTextField.setText(strBuilder.toString());

Upvotes: 6

Related Questions