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. 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.
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"? Were I to place the initializations of "uiFrame" and "firstPurchase" in main()
, "firstPurchase" would be out of scope from actionPerformed( ActionEvent e )
.
You can use the keyword this
to get a reference to the "current instance". 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");
}
}