我正在尝试在数组循环中动态创建按钮。即使在我阅读并遵循this帖子上有人遇到类似问题并且建议在其数组中分配元素的说明后,我仍然会收到java NullPointerException错误。我这样做但仍然得到同样的错误。有人可以告诉我哪里出错了吗?这是我的代码:
@Override
protected void onMain_SavePersonAction(final Component c, ActionEvent event) {
// declares an array of integers
final String[] anArray;
// allocates memory for 8 values
anArray = new String[]{"100","200","400","500","600","700","800","900"};
Button[] button = new Button[anArray.length];
for (int i = 0; i < anArray.length; i++) {
button[i].setIcon(fetchResourceFile().getImage("personIcon.png"));
button[i].setText("Member: "+i);
button[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
findName().setText("Firstname ");
findVorname().setText("Secondname ");
findFamMname().setText("Firstname Secondname" );
findFamMname().setIcon(fetchResourceFile().getImage("personIcon.png"));
findFamMname2().setText("Firstname Secondname ");
findFamMname2().setIcon(fetchResourceFile().getImage("personIcon.png"));
findDeleteMember().setVisible(true);
c.getComponentForm().revalidate();
c.getComponentForm().repaint();
}
});
findFamilyMembers().addComponent(button[i]);
}
c.getComponentForm().revalidate();
c.getComponentForm().repaint();
}
答案 0 :(得分:1)
在创建任何项目并将它们放入数组之前,您正在使用Button []数组中的项目。想象一下类似于空蛋箱的一系列物体。你不能用鸡蛋盒制作煎蛋卷,直到你第一次用鸡蛋填充它!
改变这个:
for (int i = 0; i < anArray.length; i++) {
button[i].setIcon(fetchResourceFile().getImage("personIcon.png"));
到此:
for (int i = 0; i < anArray.length; i++) {
button[i] = new Button(); // you need to first create and assign a button object!
button[i].setIcon(fetchResourceFile().getImage("personIcon.png"));
更重要的是,您需要学习如何调试NPE(NullPointerException)的一般概念。 您应该仔细检查抛出异常的行,找出哪个变量为null,然后追溯到您的代码中以查看原因。你会一次又一次地碰到这些,相信我。