调用javax.swing.JList.getSelectedIndex()报错this.newList为null如何解决
问题根因
你遇到的空指针异常和Cell Renderer无关,是变量作用域遮蔽问题:
你已经在类顶部声明了成员变量private JList newList, cancelledList;,但在构造方法中又写了JList newList = new JList(newModel);,这行代码新创建了一个局部作用域的newList,和类成员变量完全独立。构造方法执行完后,类成员变量this.newList始终没有被赋值,保持为null,在actionPerformed里调用newList.getSelectedIndex()自然会触发空指针。
除此之外你的代码还存在其他同类未初始化问题:
- 成员变量
JButton right, left、DefaultListModel cancelModel、JList cancelledList全部未完成初始化,部分在构造方法中也被同名局部变量覆盖 cancelledList相关的布局逻辑完全缺失,没有被添加到面板中
具体修复方案
- 构造方法中直接给成员变量赋值,不要创建同名局部变量
将构造方法内的对应代码修改为:
// 不要加JList前缀,直接给成员变量赋值 this.newList = new JList(newModel); newList.setCellRenderer(new listCellRenderer()); JScrollPane newScrollPane = new JScrollPane(newList); JPanel buttons = new JPanel(); // 不要加JButton前缀,直接给成员变量赋值 this.right = new JButton("=>"); this.left = new JButton("<=");
- 补全缺失的初始化代码
构造方法开头补全cancelModel初始化:
newModel = new DefaultListModel(); cancelModel = new DefaultListModel(); // 新增这行
- 参考
newList的布局逻辑,补全cancelledList的界面渲染代码,将其添加到面板中,避免后续调用cancelledList时也出现空指针。
补充说明
你当前写的listCellRenderer逻辑没有问题,不需要修改,只需要完成上述变量初始化修复即可解决报错。
内容的提问来源于stack exchange,提问作者Mr. Goose
相关产品推荐
相关产品推荐

