简体   繁体   中英

Why Gtk TextBuffer onChanged is called twice after using setText?

I'm trying to have a function called everytime the contents of a TextBuffer change, either by using buffer.setText("...") or when the user types something, but after using setText, the function is called twice (instead of once).

package com.example;

import org.gnome.gtk.*;

public class Main {

public static void main(String[] args) {
    Gtk.init(args);
    Window w = new Window();
    w.setDefaultSize(200, 200);

    TextBuffer buffer = new TextBuffer();
    buffer.setText("first text");
    TextView textView = new TextView(buffer);

    buffer.connect(new TextBuffer.Changed() {
        @Override
        public void onChanged(TextBuffer textBuffer) {
            System.out.println("onChange called with " + textBuffer.getText());
        }
    });

    buffer.setText("second text");
    buffer.setText("third text");

    w.add(textView);
    w.connect((Window.DeleteEvent) (source, event) -> {
        Gtk.mainQuit();
        return false;
    });
    w.showAll();
    Gtk.main();
}
}

This example prints

onChange called with 
onChange called with second text
onChange called with 
onChange called with third text

Any idea why this happens? I'm using java-gnome 4.1 and java 1.8.

gtk_text_buffer_set_text is a combination of gtk_text_buffer_delete and gtk_text_buffer_insert . This functions emit "delete-range" and "insert-text" signals. These signals have default handlers . These handlers emit "changed" .

So in fact for a single gtk_buffer_set_text call signals are emitted in the following order:

  1. "delete-range"
  2. "changed"
  3. "insert-text"
  4. "changed"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM