-2

I am trying to call a method from a other class but here is the problem:

The main class imports the second class with this:

Sc secondclass = new Sc();

The main class also contains this method:

public void home_open() {
    for (int i = 0; i < buttons.length; i++) {
        buttons[i].setVisible(false);
    }
}

If I want to import this into the second class:

Mc mainclass = new Mc();

A loop will happen, if I want to import it in this way:

Mc mainclass;

This error will occur:

"this.this$0.mainclass" is null

My Goal is to call a method in the main class.

Abra
  • 15,674
  • 6
  • 30
  • 39
StackKaan
  • 3
  • 3
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Progman Nov 14 '21 at 10:01

1 Answers1

0

Change the constructor of the second class to

public class Sc {
    private Mc mc;

    /**
     * Constructor
     */
    public Sc(Mc mc) {
        this.mc = mc;
    }
}

and call the constructor like so

Mc mainclass = new Mc();
Sc secondclass = new Sc(mainclass);

Now you can call methods of class Mc via the mc member of class Sc.

EDIT

Based on the [pseudo] code linked to in this comment, consider the following.

Class Home

package homeshop;

import javax.swing.JButton;

public class Home {
    private JButton[] buttons;

    public Home() {
        new Shop(this);
    }

    void homeOpen() {
        for (int i = 0; i < buttons.length; i++) {
            buttons[i].setVisible(true);
        }
    }
}

Class Shop

package homeshop;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class Shop {
    private Home home;
    private JButton[] buttons;

    public Shop(Home home) {
        this.home = home;
        buttons[0].addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                home.homeOpen();
            }
        });
    }
}

Method homeOpen, in class Home, has package access so that it can be called from class Shop since both classes are in the same package. Also note that I changed the method name so as to adhere to Java naming conventions.

Abra
  • 15,674
  • 6
  • 30
  • 39