我有一个从数组填充的组合框(不一定是)。一旦做出选择,我需要使用它作为类(对象的对象)的引用并返回另一个对象值。
public class MenuItem {
static int calories;
static int fat;
static int cholesterol;
static int sodium;
static int fiber;
MenuItem( int argCal, int argFat, int argChol, int argSod, int ArgFib) {
calories = argCal;
fat = argFat;
cholesterol = argChol;
sodium = argSod;
fiber = ArgFib;
}
}
public static MenuItem salad = new MenuItem(550, 13, 30, 860, 3);
public static MenuItem Chicken = new MenuItem(680, 13, 105, 1410, 4);
因此,当他们从combobox
中挑选时,我需要返回“cholesterol =105
”或“cholesterol = 30
”。我的问题是我不能使用combobox.getSelectedItem()
将它连接到类。
答案 0 :(得分:1)
这是你可以做到这一点的一种方式。
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selected = comboBox.getSelectedItem().toString();
if(selected.equals("Salad")){
selectedCholesterol = salad.getCholesterol();
}
if(selected.equals("Chicken")){
selectedCholesterol = chicken.getCholesterol();
}
}
});
另一种方法是创建一个HashMap,并在填充组合框时输入值。像这样:
map = new HashMap<Integer, MenuItem>();
comboBox.addItem("Salad");
map.put(0, salad);
comboBox.addItem("Chicken");
map.put(1, chicken);
你的听众会看起来像这样:
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Integer index = comboBox.getSelectedIndex();
MenuItem mItem = map.get(index);
selectedCholesterol = mItem.getCholesterol();
}
});
我更喜欢第二个,因为当你有更多的MenuItem时,它的听众不会很大。