Communication between already existing classes

这一生的挚爱 提交于 2019-12-12 04:19:25

问题


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.


回答1:


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();



来源:https://stackoverflow.com/questions/42727705/communication-between-already-existing-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!