With or without javax.swing.text.Document

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 one

if(pos!= -1){
    d.remove(pos, word1.length());
    d.insertString(pos, word2.toUpperCase(), null);
}
+5
source share
2 answers

He ultimately does the same.

Go to the source code JTextArea here , where you may find that it does the same. I also copied the method here, where you can find what it does

d.remove(pos, word1.length());
    d.insertString(pos, word2.toUpperCase(), null);

in case of a call:

 t.replaceRange(word2.toUpperCase(), pos, pos+ word1.length());

method.

The source code of the class method 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     }
+8
source

I agree with Bhavik, even the listeners of the document will not notice any difference:

txt.getDocument().addDocumentListener(new DocumentListener() {
    @Override
    public void removeUpdate(DocumentEvent pE) {
        System.out.println("removeUpdate: "+pE);
    }
    @Override
    public void insertUpdate(DocumentEvent pE) {
        System.out.println("insertUpdate: "+pE);
    }
    @Override
    public void changedUpdate(DocumentEvent pE) {
        System.out.println("changedUpdate: "+pE);
    }
});

will be made in both cases:

removeUpdate: [javax.swing.text.GapContent$RemoveUndo@97c87a4 hasBeenDone: true alive: true]
insertUpdate: [javax.swing.text.GapContent$InsertUndo@4ead24d9 hasBeenDone: true alive: true]
-1
source

All Articles