2012-05-12 8 views
5

Dato cheCon o senza 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); 

Qual è la differenza tra ...
questo

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

e questo

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

risposta

8

In fin dei conti fa la stessa cosa.

Vai al codice sorgente di JTextAreahere, dove puoi scoprire che sta facendo la stessa cosa. Ho copiato il metodo qui anche il luogo dove si può trovare che si sta facendo

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

in caso di chiamare:

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

metodo.

codice sorgente del metodo della classe è inferiore

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

curioso: perché la taglia? non sei felice della tua risposta? – kleopatra

-1

Sono d'accordo con Bhavik, anche documentare gli ascoltatori non vedrà alcuna differenza:

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

produrrà in entrambi i casi :

removeUpdate: [[email protected] hasBeenDone: true alive: true] 
insertUpdate: [[email protected] hasBeenDone: true alive: true] 
Problemi correlati