jakubek278
jakubek278

Reputation: 41

Communication between already existing classes

I am sorry if this question seems pretty basic and there is already an answer for that, but unless I make it into a proper question, google won't find it.

I have a main class that is a JFrame(there is and will be only one object, let's call it "main"), it creates and calls another JFrame class(let's call it window2), however, I still need this window2 to call methods from the already existing main class. Normally window2 would have something like Main mainMenu = new Main();. But this obviously creates a new object of main, I still want to refer to the already existing object and get information from it.

Upvotes: 0

Views: 55

Answers (1)

benji2505
benji2505

Reputation: 106

Dependency Injection. The answer depends on whether your Main class is static, but let's assume it is not:

  • Create a Main reference in Window2: Main main;
  • Create a method in Window2: public void injectMainInstance(Main main){this.main=main}
  • In Main you have the Window2 instance window2. Call window2.injectMainInstance(this);

You should be good to go now in Window2 with main.mainMethodTBUsed();

Upvotes: 1

Related Questions