简体   繁体   English

将应用程序类引用传递给构造函数(Java)

[英]Passing an Application Class Reference to Constructor (Java)

I have an application class, as shown directly below, which instantiates objects from i) a UI class I wrote that extends JFrame and implements ActionListener, and ii) a simple "Invoice" class. 我有一个应用程序类,如下所示,该类从i)实例化对象:i)我编写的扩展JFrame并实现ActionListener的UI类,以及ii)简单的“发票”类。 The former will be used as a main interface that accepts text entry, for particular values ("invoice number"), and passes those values to the latter class (invoice). 前者将用作主界面,接受特定值(“发票编号”)的文本输入,并将这些值传递给后一类(发票)。 I would like to extend the application class (in which main is implemented) to allow an actionPerformed() method to be implemented in it (not within main() of course) to listen to the press of one of two buttons within the UI class, creating a new instance of the Purchase class on the event, that will in turn pass a 'this' reference to the single UI class instance's button.addActionListener() method. 我想扩展应用程序类(在其中实现main),以允许在其中实现actionPerformed()方法(当然不在main()内),以侦听UI类中两个按钮之一的按下,在事件上创建Purchase类的新实例,该实例将依次向单个UI类实例的button.addActionListener()方法传递“ this”引用。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class CreatePurchase implements ActionListener {

boolean isInterface = true;
CreatePurchase testing = new CreatePurchase();
SupportiveJFrame uiFrame = new SupportiveJFrame( testing, "Southwest Invoice Systems", isInterface );   
Purchase firstPurchase = new Purchase( uiFrame, true );


public static void main( String args[] ){





}

public void actionPerformed( ActionEvent e ){

    Object source = e.getSource();

    if( source == uiFrame.newInvoice){

        //New object created here


    }

}       
}   

My question is, How can a reference to the application class be passed to the UI constructor thereby allowing it to be passed to the JButton "newObject"? 我的问题是,如何将对应用程序类的引用传递给UI构造函数,从而允许将其传递给JButton“ newObject”? Were I to place the initializations of "uiFrame" and "firstPurchase" in main(), "firstPurchase" would be out of scope from actionPerformed( ActionEvent e ). 如果将“ uiFrame”和“ firstPurchase”的初始化放置在main()中,则“ firstPurchase”将超出actionPerformed(ActionEvent e)的范围。

You can use the keyword this to get a reference to the "current instance". 您可以使用关键字this获得对“当前实例”的引用。 I'm not sure which class you want to add it to, but here's an example that should demonstrate the idea: 我不确定你要将它添加到哪个类中,但这里有一个例子可以证明这个想法:

public class A {
    private B owner;
    public A(B owner) {this.owner = owner;}

    public void callOwnerDoSomething() {owner.doSomething();}
}

public class B {

    public A theA = new A(this);

    public static void main(String[] args) {
        new B().theA.callOwnerDoSomething(); // prints "Hello"
    }

    public void doSomething() {
        System.out.println("Hello");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM