繁体   English   中英

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

[英]What is the proper way to feed data to JComboBox?

将数据提供给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都需要更新数据,因为数组中的字符串可能与第一次使用组合框时不同。

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

虽然有时会适当更换 ComboBoxModel使用setModel()如图所示这里 ,您可能需要更新使用替代模型removeAllElements()调用,然后循环addElement()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM