【问题标题】:Using replace with DocumentListener使用 DocumentListener 替换
【发布时间】:2013-01-20 12:01:52
【问题描述】:

我有两个文本区域。当我在第一个 textarea 中输入内容时,它会显示在带有 documentlistener 的第二个文本区域中。我想用 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 替换为 hello,然后会显示在 area2 中。但是,它并没有改变这个词。那么我做错了什么?

谢谢!

【问题讨论】:

    标签: java replace documentlistener


    【解决方案1】:

    字符串是不可变的;他们不能改变。所以:

    你好。替换(“嘿”,“你好”);

    应该是:

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

    Replace 方法必须返回一个新字符串,其中包含您所做的更改,因为它无法修改原始字符串。

    【讨论】:

      猜你喜欢
      • 2014-12-11
      • 2014-12-26
      • 2013-10-11
      • 2012-10-25
      • 2017-07-16
      • 2011-11-11
      • 2011-01-18
      • 2013-04-28
      • 2013-07-03
      相关资源
      最近更新 更多