在我的 GUI 中,我有 3 个单选按钮,它们属于同一个 ButtonGroup。我试图得到它,以便在单击任何一个按钮时,都会出现一个 JList 。在我的动作监听器中,我编写了 JLists,但是当我尝试运行它时,我得到了 NullPointerException。我尝试将 JList 放在动作侦听器之外并且它可以工作,所以我很确定我的动作侦听器有问题。我的按钮按照我的意愿出现在 GUI 中。
它是主 GUI 类中的一个内部类:
rbGenCancers = new JRadioButton("genCan");
rbRelCancers = new JRadioButton("relCan");
rbCancers = new JRadioButton("nonC");
ButtonGroup bg = new ButtonGroup();
bg.add(rbGenCancers);
bg.add(rbRelCancers);
bg.add(rbCancers);
JPanel rbButtons = new JPanel(new FlowLayout(3, 2, 2));
rbButtons.add(rbGenCancers);
rbButtons.add(rbRelCancers);
rbButtons.add(rbCancers);
//added to the JFrame correctly through GridBagLayout and GridBagConstraints
public class RadioButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
switch(e.getActionCommand()) {
case "genCan":
listModel = new DefaultListModel();
for(int i = 0; i < 8; i++) {
cancerNames = _controller.selectGeneralCancer(i);
listModel.addElement(cancerNames);
}
cancerList = new JList(listModel);
cancerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cancerList.setSelectedIndex(-1);
cancerList.setVisibleRowCount(3);
cancerListScroller = new JScrollPane(cancerList);
break;
case "relCan":
listModel = new DefaultListModel();
for(int i = 0; i < 22; i++) {
split = _controller.readCancer(i);
cancerNames = split[0];
listModel.addElement(cancerNames);
}
cancerList = new JList(listModel);
cancerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cancerList.setSelectedIndex(-1);
cancerList.setVisibleRowCount(3);
cancerListScroller = new JScrollPane(cancerList);
break;
case "nonC":
listModel = new DefaultListModel();
for(int i = 22; i < 36; i++) {
split = _controller.readCancer(i);
cancerNames = split[0];
listModel.addElement(cancerNames);
}
cancerList = new JList(listModel);
cancerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cancerList.setSelectedIndex(-1);
cancerList.setVisibleRowCount(3);
cancerListScroller = new JScrollPane(cancerList);
break;
}
}
}
下面是抛出的异常:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1086)
at java.awt.Container.add(Container.java:998)
at javax.swing.JFrame.addImpl(JFrame.java:562)
at java.awt.Container.add(Container.java:966)
at Cancer.gui.CancerGUI.<init>(CancerGUI.java:306)
at Cancer.run.CancerApp.main(CancerApp.java:19)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
这是执行所有代码的类。打印堆栈中的第 19 行对应于 CancerGUI _gui = new CancerGUI(); CancerGUI 中的第 306 行对应于我通过 GridBagConstraints 将cancerListScroller 添加到 JFrame 的位置。
public class CancerApp {
public static void main(String[] args) {
CancerGUI _gui = new CancerGUI();
Disease _disease = new Disease();
CancerController _controller = new CancerController(_disease, _gui);
_gui.setController(_controller);
CancerApp _app = new CancerApp();
_app.run(_gui);
}
public void run(CancerGUI _gui) {
_gui.setVisible(true);
}
}