1

What is the proper way to feed data to JComboBox? I am trying to feed a String array to the JComboBox that was initiated before, and I am getting a NullPointerException.

Code:

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

Error:

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

Edit: My problem here is that 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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Adam Rich
  • 86
  • 2
  • 10
  • What's the data type of `currentGames.get(currentGame).currentPlayers()`? A List? Map? ... – STaefi May 29 '16 at 09:24
  • Is it multithreaded? Make sure there is no race condition. E.g. `currentGames.get(currentGame).currentPlayers()` could potentially return number which will become non-actual during the loop execution, should there be another thread adding/removing elements to/from the list. Check GUI elements with static data first. – Andrey Lebedenko May 29 '16 at 09:44
  • `currentGames.get(currentGame).currentPlayers()` return an int and `currentGames.get(currentGame).getPlayer(i).getId()` returns a string – Adam Rich May 29 '16 at 09:48
  • it is not multithreaded. My problem here is that i need to update the data in the JcomboBox every time I want to use because the Strings in the array might be different than when i used the ComboBox the first time. The compiler is giving me the exception when the line `playersBox.setModel( model);` is invoked – Adam Rich May 29 '16 at 09:56
  • Voting to reopen, as the `NullPointerException` is incidental to the nominal question. – trashgod May 29 '16 at 19:59

1 Answers1

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.

Although it is sometimes appropriate to replace the ComboBoxModel using setModel(), as shown here, you may want to update the model in place using removeAllElements() followed by a loop that invokes addElement().

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045