简体   繁体   中英

How do I implement a Class into an ActionListener?

As the title indicates I am looking to implement an existing class from my Java project into an ActionListener class. To help you understand my issue, I will first explain the scenario:

I have been assigned to create a Graphics package; this will take user input from a CommandPanel JTextField to draw specified lines from the user when the conditional action has been met and completed. The GUI consists of 4 classes, 3 of which extend JPanels .

The problem that I have is trying to implement the specified GraphicsPanel class into my CommandPanel ActionListener .

I want to be able to draw a line when the requirement has been met to ensure that the line is drawn in the same GraphicsPanel as viewed in my main class (not included here).

The statement gp works as intended in the public CommandPanel(GraphicsPanel gp) segment however when I try to call gp into my ActionListener to draw a line in that panel, it fails to recognise it as a pre-existing class.

Further clarification can be made to ensure that you understand the problem at hand; any help would be greatly appreciated. :-D

You have to store gp as a instance variable in your CommandPanel when the constructor is called:

private GraphicsPanel gp;
public CommandPanel(GraphicsPanel gp) {
    this.gp = gp;
}

Alternatively, hand down gp to the ActionListener and store it in a instance variable in there:

public CommandPanel(GraphicsPanel gp) {
    ButtonListener listener = new ButtonListener(gp);
}

public class ButtonListener implements ActionListener {
    GraphicsPanel gp;
    public ButtonListener(GraphicsPanel gp){
        this.gp = gp;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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