简体   繁体   中英

Using class members in ActionListener

I am having issue using a timer. I create a ship that shoots upwards at random times (the ship is moving from left to right.)

The point is actually that it will shoot from random places on the X axis.

From my search I understood that I have to use ActionListener inside my Ship class and inside it I am supposed to create the shot. My problem is the following:

How can I use the Ship class members inside the `actionPerformed function? So that I will know the location of the ship at the time and create the shot location accordingly.

You can make the ActionListener a non-static inner class. Such classes have access to members of the outer class:

public class Ship {
    private int location;

    public Ship() {
        <gui>.addActionListener(new Listener());
    }

    private class Listener implements ActionListener {
         void actionPerformed(ActionEvent e) {
             // here we can access location and other Ship members
         }
    }
}

If you are using Java8 you can drop the action listener class and use a method handle to be notified when an action event occurs:

public class Ship {
    private int location;


    public Ship() {
        <gui>.addActionListener(this::onAction);
    }

    private void onAction(ActionEvent e) {
        ...
    }
}

You can do one of the following:

  • Declare the local variables you need to access inside the actionListener as final .
  • Declare the variables you need to access inside the actionListener as class members.

Good Luck.

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