import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class MapCombo {
private JPanel getContent() {
final Map<String, Customer> map = getMap();
JComboBox combo = new JComboBox();
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
while(it.hasNext()) {
String key = it.next();
combo.addItem(key);
}
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox)e.getSource();
String key = (String)combo.getSelectedItem();
Customer customer = map.get(key);
System.out.println(customer);
}
});
JPanel panel = new JPanel();
panel.add(combo);
return panel;
}
private HashMap<String, Customer> getMap() {
Customer[] customers = new Customer[4];
customers[0] = new Customer("Helen", "Oregon", 12);
customers[1] = new Customer("Paul", "Idaho", 99);
customers[2] = new Customer("Sue", "Texas", 22);
customers[3] = new Customer("Oscar", "Utah", 42);
HashMap<String, Customer> map = new HashMap<String, Customer>();
for(int i = 0; i < customers.length; i++) {
String key = customers[i].name;
Customer value = customers[i];
map.put(key, value);
}
return map;
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MapCombo().getContent());
f.setSize(200,100);
f.setVisible(true);
}
}
class Customer {
String name;
String location;
int idNumber;
Customer(String name, String loc, int id) {
this.name = name;
location = loc;
idNumber = id;
}
public String toString() {
return "Customer[name:" + name +
" location:" + location +
" idNumber:" + idNumber + "]";
}
}