JList - `setListData()` 导致 `getSelectedValue()` 为 return null

JList - `setListData()` causes `getSelectedValue()` to return null

当我创建我的 JList 时,我可以使用 getSelectedValue() 打印出我在列表中选择的字符串。一旦我更改列表中的内容,返回的所有内容都是空的。

创建列表后我有这个:

matchList.setModel(new javax.swing.AbstractListModel<String>() {
    String[] playerList = {"test"};
    public int getSize() { return playerList.length; }
    public String getElementAt(int i) { return playerList[i]; }
});

稍后我将 JList 更改为包含一个字符串数组:

matchList.setListData(Bracket.wr1);

数组中的所有内容都显示在 JList 中,但如果我尝试使用 getSelectedValue() 来获取正在显示的字符串,它只是 returns null。

我做错了什么?

好像没有选择了。根据 Oracle Documentation getSelectedValue()

[r]eturns null if there is no selection.

因此,如果不再有默认选择,您可能应该将第一个元素设置为默认值:

list.setSelectedIndex(0);