靈活的Java鍵/值集合類我有一個存儲密鑰和值的模型類:極品的JComboBox
public class KeyValue {
private Object key;
private String value;
KeyValue() {
}
KeyValue (Object key, String value) {
this.key=key;
this.value=value;
}
public Object getKey() {
return this.key;
}
public void setKey(Object key) {
this.key=key;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value=value;
}
@Override
public String toString() {
return this.value;
}
}
我使用這個類來填充JComboBox
的型號:
for (int i = 0; i < universes.length; i++) {
ComboBox_Universes.addItem(new KeyValue(infoObject.ID,infoObject.title));
}
我想重構這個邏輯來使用Java集合類(稱爲KeyValueCollection
),它可以支持兩個目標:
1)KeyValueCollection
可以是u sed來填充JComboBox
的模型。喜歡的東西:
//get a KeyValueCollection filled with data from helper class
KeyValueCollection universeCollection = Repository.getUniverseCollection();
//use this collection as the JComboBox's model
ComboBox_Universes.setModel(universeCollection);
2)我可以使用KeyValueCollection
一鍵轉換爲值:
//ID retrieve from another control
int universeID = (int)this.Table_Values.getModel().getValueAt(row, COLUMN_ID);
//convert ID to name
String universeName = universeCollection.get(universeID).getValue();
在.NET的世界裏,我會用這個KeyedCollection類的,但我對Java不太熟悉。
非常感謝幫助。
三個問題: 1.什麼是設置SelectedItem的語法?這個Foo的一部分是[foo]我......對不起。 Map.Entry item = new Foo (「2」,「red」); model.setSelectedItem(item); 2.如果我想要一個setSelectedKey()方法,那麼我需要從TreeMap中找到正確的Map.Entry,然後調用setSelectedItem,是否正確? 3.理想情況下,組合框的值將按字母順序排序。我假設我需要對HashMap的值進行排序。還有另一種更簡單的方法嗎? –
craig
2010-01-22 03:56:59
@克雷格:我希望我的編輯能夠滿足您的需求。 – 2010-01-22 09:17:58
應該不是setSelectedKey()方法讀: 公共無效setSelectedKey(String鍵){ //調用設置變量和觸發事件 setSelectedItem(values.ceilingEntry(鍵))的方法; } – craig 2010-01-22 14:06:59