With or without the javax.swing.text.Document
java, jtextarea, swing
Solution
Ultimately it does the same thing.
Go to the source code of `JTextArea` here, where you can find that it is doing the same thing. I have copied the method here also where you can find that it is doing
d.remove(pos, word1.length());
d.insertString(pos, word2.toUpperCase(), null);
in case of calling:
t.replaceRange(word2.toUpperCase(), pos, pos+ word1.length());
method.
Source code of the method of the class is below
public void replaceRange(String str, int start, int end) {
490 if (end < start) {
491 throw new IllegalArgumentException ("end before start");
492 }
493 Document doc = getDocument();
494 if (doc != null) {
495 try {
496 if (doc instanceof AbstractDocument) {
497 ((AbstractDocument)doc).replace(start, end - start, str,
498 null);
499 }
500 else {
501 doc.remove(start, end - start);
502 doc.insertString(start, str, null);
503 }
504 } catch (BadLocationException e) {
505 throw new IllegalArgumentException (e.getMessage());
506 }
507 }
508 }
Problem
Given that ``` JTextArea t = new JTextArea(); Document d = t.getDocument(); String word1 = "someWord"; String word2 = "otherWord" int pos = t.getText().indexOf(word1,i); ``` What is the difference between ... this ``` if(pos!= -1){ t.replaceRange(word2.toUpperCase(), pos, pos+ word1.length()); } ``` and this ``` if(pos!= -1){ d.remove(pos, word1.length()); d.insertString(pos, word2.toUpperCase(), null); } ```