我有一个应用程序类,如下面所示,它实例化来自i)我编写的扩展JFrame并实现ActionListener的UI类,以及ii)一个简单的" Invoice"类。前者将用作接受文本输入的主界面,用于特定值("发票编号"),并将这些值传递给后一类(发票)。我想扩展应用程序类(在其中实现main)以允许在其中实现actionPerformed()方法(当然不在main()内)来监听UI类中两个按钮之一的按下,在活动中创建一个新的Purchase类实例,然后通过一个' this'引用单个UI类实例的button.addActionListener()方法。
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
}
}
}
我的问题是,如何将对应用程序类的引用传递给UI构造函数,从而允许将它传递给JButton" newObject"?如果我要初始化" uiFrame"和" firstPurchase"在main()," firstPurchase"将超出actionPerformed(ActionEvent e)的范围。
答案 0 :(得分:0)
您可以使用关键字this
来获取对"当前实例"的引用。我不确定您要将哪个课程添加到其中,但这里有一个示例可以证明这个想法:
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");
}
}