2012-05-12 6 views
5

Dado queCon o sin el javax.swing.text.Document

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

¿Cuál es la diferencia entre ...
este

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

y esto

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

Respuesta

8

En definitiva, hace lo mismo.

Vaya al código fuente de JTextAreahere, donde puede ver que está haciendo lo mismo. He copiado el método aquí también donde se puede encontrar que se está haciendo

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

en caso de llamar:

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

método.

El código fuente del método de la clase está por debajo de

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  } 
+1

curious: why the bounty? ¿no estás contento con tu propia respuesta? – kleopatra

-1

Estoy de acuerdo con Bhavik, incluso documentar los oyentes no va a ver ninguna diferencia:

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); 
    } 
}); 

producirá en ambos casos :

removeUpdate: [[email protected] hasBeenDone: true alive: true] 
insertUpdate: [javax.swing.text.GapContent$I[email protected] hasBeenDone: true alive: true] 
Cuestiones relacionadas