有或没有javax.swing.text.Document

Jaz*_*azz 5 java swing jtextarea

鉴于

JTextArea t = new JTextArea();
Document d = t.getDocument();
String word1 = "someWord";
String word2 = "otherWord"
int pos = t.getText().indexOf(word1,i);
Run Code Online (Sandbox Code Playgroud)

有什么区别......
这个

if(pos!= -1){
    t.replaceRange(word2.toUpperCase(), pos, pos+ word1.length());
}
Run Code Online (Sandbox Code Playgroud)

还有这个

if(pos!= -1){
    d.remove(pos, word1.length());
    d.insertString(pos, word2.toUpperCase(), null);
}
Run Code Online (Sandbox Code Playgroud)

Bha*_*ani 8

最终它也做同样的事情.

转到JTextArea 这里的源代码,那里你可以发现它正在做同样的事情.我已经在这里复制了方法,你可以在那里找到它正在做的事情

d.remove(pos, word1.length());
    d.insertString(pos, word2.toUpperCase(), null);
Run Code Online (Sandbox Code Playgroud)

如果打电话:

 t.replaceRange(word2.toUpperCase(), pos, pos+ word1.length());
Run Code Online (Sandbox Code Playgroud)

方法.

该类方法的源代码如下

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     }
Run Code Online (Sandbox Code Playgroud)