2017-05-31 16 views
0

我試圖放置與我的視圖上的偵聽器鏈接的ObservableMap>。作爲值類型不觸發的HashMap的ObservableMap MapChangeListener

這是我使用的代碼:

ObservableMap<Integer, HashMap<String, Integer>> map = FXCollections.observableHashMap(); 

    map.addListener((MapChangeListener.Change<? extends Integer, ? extends HashMap<String, Integer>> change) -> { 
     System.out.println("Changed key: " + change.getKey()); 
    }); 

    HashMap<String, Integer> store1 = new HashMap<>(); 
    store1.put("apple", 100); 
    store1.put("strawberry", 123); 
    store1.put("lemon", 165); 
    map.put(1, store1); 

    HashMap<String, Integer> store2 = new HashMap<>(); 
    store2.put("peach", 45); 
    store2.put("blackberry", 90); 
    store2.put("melon", 10); 
    map.put(2, store2); 

    HashMap<String, Integer> cpStore2 = map.get(2); 
    cpStore2.put("peach", 40); 
    map.put(2, cpStore2); 

如果我執行,我得到這樣的:

Changed key: 1 
Changed key: 2 

所以我的問題是,當我做一個更新的地圖上有沒有任何事件被觸發。我實際上需要這個。

有人知道我該怎麼做嗎?

回答

1

該事件剛剛解僱如果值的變化。但是你使用相同的密鑰來放置相同的地圖。所以很清楚,沒有更改事件。爲了確保觸發事件,您可以創建與現有值的新地圖,並把新的一個:

HashMap<String, Integer> cpStore2 = new HashMap<String, Integer>(map.get(2)); 
// cpStore2 is another map than store2 but with the same values 
cpStore2.put("peach", 40); 
map.put(2, cpStore2); 
+0

謝謝,這正是我想要的 –

0

我看到ObservableMapWrapper類的工具,其中FXCollections.observableHashMap();返回,下面的代碼:

@Override 
public V put(K key, V value) { 
    V ret; 
    if (backingMap.containsKey(key)) { 
     ret = backingMap.put(key, value); 
     if (ret == null && value != null || ret != null && !ret.equals(value)) { 
      callObservers(new SimpleChange(key, ret, value, true, true)); 
     } 
    } else { 
     ret = backingMap.put(key, value); 
     callObservers(new SimpleChange(key, ret, value, true, false)); 
    } 
    return ret; 

所以,你可以觸發聽衆在您的代碼中添加或更新一個新的value.But:

HashMap<String, Integer> cpStore2 = map.get(2); 
cpStore2.put("peach", 40); 
map.put(2, cpStore2); 

的cpStore2是關鍵2的舊值,你可以這樣做:

HashMap<String, Integer> cpStore2 = new HashMap<>(); 
    cpStore2.put("peach", 40); 
    map.put(2, cpStore2); 

你會觸發listener.See以上代碼的結果:

Changed key: 1 
Changed key: 2 
Changed key: 2 
+0

是它可以工作,我必須手動的我的老地圖中的每個元素添加到新的?因爲如果地圖很大,那將意味着時間問題? –

+0

爲了提高性能,您可以從map中移除key的映射。然後偵聽器應該過濾操作。例如,'if(change.wasAdded())System.out.println(「Changed key:」+ change .getKey()); }' – dabaicai