简体   繁体   English

在ActionListener中使用类成员

[英]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. 关键是实际上它将在X轴上的任意位置拍摄。

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. 通过搜索,我了解到必须在Ship类中使用ActionListener并且应该在其中创建镜头。 My problem is the following: 我的问题如下:

How can I use the Ship class members inside the `actionPerformed function? 如何在actionPerformed函数中使用Ship类成员? 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. 您可以使ActionListener成为非静态内部类。 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: 如果使用的是Java8,则可以删除操作侦听器类,并使用方法句柄在发生操作事件时得到通知:

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 . 声明需要在actionListener内部访问的局部变量作为final
  • Declare the variables you need to access inside the actionListener as class members. 声明需要在actionListener内部访问的actionListener作为类成员。

Good Luck. 祝好运。

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

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