有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从数组循环创建动态按钮时出现java NullPointerException错误的代码名

我正在尝试从数组中动态创建循环中的按钮。即使在我阅读并遵循thispost上的说明(其中有人有类似的问题,并被建议在他的数组中分配元素)之后,我仍然会收到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();

}

共 (1) 个答案

  1. # 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,然后追溯到代码中以了解原因。相信我,你会一次又一次地碰到这些