2016-05-29 48 views
1

將數據提供給JComboBox的正確方法是什麼?我正嘗試將String數組提供給之前啓動的JComboBox,並且我得到了NullPointerException將數據提供給JComboBox的正確方法是什麼?

代碼:

public void readPlayers(){ 
    String[] arr = new String[currentGames.get(currentGame).currentPlayers()]; 
    for(int i = 0; i <currentGames.get(currentGame).currentPlayers(); i++){ 
     arr[i] = "Player " + (i + 1) + currentGames.get(currentGame).getPlayer(i).getId(); 
    } 
    DefaultComboBoxModel model = new DefaultComboBoxModel(arr); 
    playersBox.setModel( model); 
} 

錯誤:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 

編輯:我在這裏的問題是,我需要在JComboBox我想使用它,因爲在字符串每次更新數據數組可能與我第一次使用組合框時不同。

+0

什麼是'currentGames.get(currentGame).currentPlayers()'的數據類型?一個列表?地圖? ... – STaefi

+0

它是多線程的嗎?確保沒有競爭條件。例如。 currentGames.get(currentGame).currentPlayers()'可能會返回在循環執行過程中將變爲非實際的數字,如果有另一個線程將元素添加到/從列表中刪除。首先用靜態數據檢查GUI元素。 –

+0

'currentGames.get(currentGame).currentPlayers()'返回一個int和'currentGames.get(currentGame).getPlayer(i).getId()'返回一個字符串 –

回答

2

I need to update the data in the JComboBox every time I want to use it because the strings in the array might be different than when I used the combo box the first time.

雖然有時適當使用setModel()取代ComboBoxModel,如圖所示here,你可能要更新使用removeAllElements()接着一個循環,調用addElement()模型到位。

+1

Thx。它與您介紹的另一種方式一起工作 –

相關問題