现有类之间的通信 [英] Communication between already existing classes

查看:44
本文介绍了现有类之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这个问题看起来很基本,已经有了答案,但是除非我将其变成一个适当的问题,否则Google找不到它.

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.

我有一个主类,它是一个JFrame(存在并且将是一个对象,我们称它为"main"),它创建并调用了另一个JFrame类(我们将其称为window2),但是,我仍然需要这个window2从已经存在的主类中调用方法.通常,window2的内容类似于Main mainMenu = new Main();. 但这显然创建了main的新对象,我仍然想引用已经存在的对象并从中获取信息.

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.

推荐答案

依赖注入.答案取决于您的Main类是否是静态的,但让我们假设它不是:

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

  • 在Window2中创建主要参考:主要主要;
  • 在Window2中创建一个方法:public void injectMainInstance(Main main){this.main = main}
  • 在Main中,您拥有Window2实例window2.呼叫window2.injectMainInstance(this);

您现在应该可以通过main.mainMethodTBUsed();进入Window2.

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

这篇关于现有类之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆