I have two textareas. When I type something in the first textarea, it shows up in the second one with documentlistener. I want to use replace to replace certain words with different words (like a translator).
My DocumentListener looks like this:
DocumentListener documentListener = new DocumentListener() {
public void changedUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
public void insertUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
public void removeUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
private void printIt(DocumentEvent documentEvent) {
DocumentEvent.EventType type = documentEvent.getType();
String typeString = null;
if (type.equals(DocumentEvent.EventType.CHANGE)) {
}
else if (type.equals(DocumentEvent.EventType.INSERT)) {
String hello = area1.getText();
hello.replace("hei", "hello");
area2.setText(hello);
}
else if (type.equals(DocumentEvent.EventType.REMOVE)) {
String hello = area1.getText();
area2.setText(hello);
}
}
};
This doesn't work though. I thought the hello.replace would replace the word hei typed in area1 with hello, which would be displayed in area2. However, it doesnt change the word. So what am I doing wrong?
Thanks!
Strings are immutable; they can't be changed. And so:
hello.replace("hei", "hello");
Should be:
hello = hello.replace("hei", "hello");
Replace method has to return you a NEW string with your changes in it because it can't modify the original.