0

2つのテキストエリアがあります。最初のテキストエリアに何かを入力すると、それはdocumentlistenerで2番目のテキストエリアに表示されます。replaceを使用して、特定の単語を別の単語(翻訳者など)に置き換えたいと思います。

私のDocumentListenerは次のようになります。

DocumentListener documentListener = new DocumentListener() {

    public void changedUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
    }
    public void insertUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
    }
    public void removeUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
    }
    private void printIt(DocumentEvent documentEvent) {
        DocumentEvent.EventType type = documentEvent.getType();
        String typeString = null;
        if (type.equals(DocumentEvent.EventType.CHANGE)) {
        }  
        else if (type.equals(DocumentEvent.EventType.INSERT)) {
            String hello = area1.getText();
        hello.replace("hei", "hello");
        area2.setText(hello);
        }
        else if (type.equals(DocumentEvent.EventType.REMOVE)) {
            String hello = area1.getText();
        area2.setText(hello);
        }
    }
};

ただし、これは機能しません。hello.replaceは、area1に入力されたheiという単語を、area2に表示されるhelloに置き換えると思いました。しかし、それは言葉を変えません。だから私は何が間違っているのですか?

ありがとう!

4

1 に答える 1

2

文字列は不変です。変更することはできません。など:

hello.replace( "hei"、 "hello");

する必要があります:

hello = hello.replace( "hei"、 "hello");

Replaceメソッドは、元の文字列を変更できないため、変更内容を含む新しい文字列を返す必要があります。

于 2013-02-05T14:24:39.033 に答える