2013-07-10 327 views
2

我試圖監聽Java JComboBox中的選擇更改。我曾嘗試使用一個ActionListener但問題是這樣的:行動聽衆都這樣做Java JComboBox監聽更改選擇事件

public void actionPerformed(ActionEvent e){ 
    JComboBox<String> source = ((JComboBox<String>)e.getSource()); 
    String selected = source.getItemAt(source.getSelectedIndex()); 

    /*now I compare if the selected string is equal to some others 
     and in a couple of cases I have to add elements to the combo*/ 
} 

東西正如你可以看到,當我需要的元素添加到組合的另一個事件被觸發,actionPerformed方法是再次呼籲,即使我不希望這樣,代碼可以循環... :( 有什麼辦法來聽,而不是選擇更改爲普通更改事件? 感謝

+0

http://stackoverflow.com/questions/58939/jcombobox-selection-change-listener –

回答

8

你可以嘗試itemStateChanged()方法ItemListener接口:

class ItemChangeListener implements ItemListener{ 
    @Override 
    public void itemStateChanged(ItemEvent event) { 
     if (event.getStateChange() == ItemEvent.SELECTED) { 
      Object item = event.getItem(); 
      // do something with object 
     } 
    }  
} 

與聽者添加到您的JComboBox:

source.addItemListener(new ItemChangeListener());