开发者

How to make a listener that listens for changes in a TreeMap?

I'm making a GUI which conjugates Spanish Verbs. It utilizes 开发者_JAVA百科a TreeMap as the main data structure, which is filled with instantiations of the class Verb. Each instantiation includes a String which contains the infinitive form of the Verb, like "hablar" or "escribir." There's a function in the GUI that allows the user to input a new Verb by typing in its infinitive and its English translation.

I want to know how to create a listener that will run some code every time that a new verb is added -- or removed -- from the TreeMap. How would I go about doing this?


You can subclass the TreeMap class, eg.

public class MyTreeMap<K, V> extends TreeMap<K, V> {
    @Override
    public V put(K key, V val) {
        V ret = super.put(key, val);
        myAddCallback(key, val);
        return ret;
    }

    @Override
    public V remove(K key) {
        V ret = super.remove(key);
        myRemoveCallback(key);
        return ret;
    }
}

Another (significantly more involved) option would be to check out AspectJ, an AOP-based JRE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜