问题
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