简体   繁体   English

从单独方法中声明的 actionPerformed 访问数组

[英]Accessing an array from actionPerformed declared in a seperate method

Apologies for the noob question beforehand.事先为菜鸟问题道歉。 Just trying to wrap my head around this.只是想解决这个问题。

My question revolves around the following code(summarized):我的问题围绕着以下代码(总结):

public class GUI extends JFrame implements ActionListener, MouseMotionListener {

  public static void main(String[] args) {
    GUI ig = new GUI();
  }

  GUI() {
    // code that sets several jpanels/buttons/labels and creates a GUI
    Object items[] = new Object[1000];
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() = X) {
      // I am trying to somehow call the array of object items here, but have had
      // little success.
    }
  }
}

It doesn't seem like I can have actionPerformed receive an array as a method because it is pre-defined as void in the library.似乎我不能让 actionPerformed 接收一个数组作为方法,因为它在库中预定义为 void。 There has to be a way to pass in the array into the method, I'm just at a loss on finding out how currently.必须有一种方法可以将数组传递给方法,我只是不知道目前如何。

I know I can declare items right before main to make it visible to actionPerformed, but I'm wondering if there's a way to call it if its declared inside GUI constructor instead?我知道我可以在 main 之前声明项目以使其对 actionPerformed 可见,但我想知道如果它是在 GUI 构造函数中声明的,是否有办法调用它?

Variables exists only in the block they are declared in. So when you write变量只存在于声明它们的块中。所以当你写

GUI()
{
    Object items[] = ...
}

you can use it only between these brackets.您只能在这些括号之间使用它。 This is called "variable scope".这称为“可变范围”。 You can move the declaration of this variable outside the constructor and make it a class field.您可以将此变量的声明移到构造函数之外,并使其成为类字段。 This means any method and constructor in your class can access it (in respect to static vs non-static access).这意味着您类中的任何方法和构造函数都可以访问它(关于静态访问与非静态访问)。 So in your case it might look like this:所以在你的情况下它可能看起来像这样:

public class GUI
{
    Object items[]; // declare it here, outside the constructor

    GUI()
    {
        // access "items" here
    }

    public void actionPerformed(ActionEvent e)
    {
        // also access "items" here
    }
}

So the steps you do are:所以你做的步骤是:

  • Declare the variable as a field at the class level, not the constructor level.在类级别而不是构造函数级别将变量声明为字段。
  • Initialize the field in your constructor with the values you want to set.使用要设置的值初始化构造函数中的字段。
  • Read/access the field in your actionPerformed() method as you want to.根据需要读取/访问actionPerformed()方法中的字段。

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

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