将数据提供给JComboBox的正确方法是什么?

时间:2016-05-29 08:41:09

标签: java swing

将数据提供给JComboBox的正确方法是什么?我正在尝试将String数组提供给之前启动的JComboBox,并且我得到NullPointerException

代码:

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中的数据,因为数组中的字符串可能与我第一次使用组合框时的字符串不同。

1 个答案:

答案 0 :(得分:2)

  

我每次想要使用它时都需要更新JComboBox中的数据,因为数组中的字符串可能与我第一次使用组合框时的字符串不同。

虽然有时候使用ComboBoxModel 替换 setModel()是合适的,如图here所示,您可能希望更新使用removeAllElements()后跟一个调用addElement()的循环的模型。

相关问题