" using GUI only ? "
I assume you mean from design view. I don't think so. Just hand code it. It's not that difficult.
Here's an example using a Student
object as the map value, and the Student
id
as the map key
. The key
is the display value in the JComboBox
. The value is retrieved from the selection by using get(id)
from the map.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class MapCombo {
public MapCombo() {
Map<Integer, Student> map = createMap();
JComboBox cbox = createComboBox(map);
cbox.setBorder(new EmptyBorder(20, 20, 20, 20));
JFrame frame = new JFrame("Map ComboBox");
frame.add(cbox);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Map<Integer, Student> createMap() {
Map<Integer, Student> map = new HashMap<>();
Student s1 = new Student(23, "Micheal Jordan");
Student s2 = new Student(6, "Lebron James");
Student s3 = new Student(3, "Chris Paul");
Student s4 = new Student(8, "Kobe Briant");
Student s5 = new Student(21, "Tim Duncan");
map.put(s1.getId(), s1);
map.put(s2.getId(), s2);
map.put(s3.getId(), s3);
map.put(s4.getId(), s4);
map.put(s5.getId(), s5);
return map;
}
private JComboBox createComboBox(final Map<Integer, Student> map) {
final JComboBox cbox = new JComboBox();
for (Integer id : map.keySet()) {
cbox.addItem(id);
}
cbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Integer id = (Integer)cbox.getSelectedItem();
System.out.println(map.get(id));
}
});
return cbox;
}
public class Student {
String name;
Integer id;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
@Override
public String toString() {
return "Name: " + name + " - Stud ID: " + id;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MapCombo();
}
});
}
}