2015-04-23 75 views
0

我有一個從數組填充的組合框(不一定是)。一旦選擇完成,我需要將它用作對類的引用(它的對象)並返回另一個對象值。將JcomboBox.getSelectedItem()連接到類

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

您可能必須將其轉換爲MenuItem。顯示偵聽器的代碼。 –

+0

你的JComboBox在哪裏? – Blip

+0

這就是關鍵,我沒有動作監聽器...... JComboBox在主要[]中,只是啓動和填充。對動作監聽器有任何想法? – user3207737

回答

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(); 

     } 
    }); 

我喜歡第二個更因爲它的聽衆不會是巨大的,當你有更多的MenuItems。

+0

謝謝Cristian,聽衆的代碼完全回答了我的問題。 – user3207737