“只使用图形用户界面?”
我假设您的意思是从设计角度来看。我不这么认为。只需手动编码即可。这并不难。
这是一个使用Student
对象作为映射值的示例,并将Student
id
用作映射key
。是 中的key
显示值JComboBox
。使用地图从选择中检索该值get(id)
。
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();
}
});
}
}