Java - 如何允许类的所有方法访问在构造函数中初始化的数组?

时间:2014-03-26 03:04:47

标签: java arrays class methods constructor

我有兴趣了解如何在类中声明和初始化JButton数组,以便同一个类的构造函数和方法都可以访问此数组。

目前,我在类定义的开头声明了JButtons和数组,并在类构造函数中初始化了数组。但是,这不允许课程的其余部分'访问数组变量的方法。

非常感谢您的帮助!

public class demo{
    public JButton one;
    public JButton two;
    public JButton three;

    public JButton demoArray[] = new JButton[3];

    public demo(){
         demoArray[0] = one;
         demoArray[1] = two;
         demoArray[2] = three;
         ....
         }

    public void actionPerformed(ActionEvent e)
    {...
        for(int i=0; i<3; i++)
        {
             demoArray[i].setEnabled(false);
        }
    }

}

2 个答案:

答案 0 :(得分:1)

在类范围中声明的变量和构造函数中的初始化应该可以在类中的任何位置访问。

如:

private/public <Class> <object>;

应该足够了,如果您需要进一步的帮助,则需要查看一些代码。

[编辑] 你发布的内容应该可以正常工作,但在你做之前

demoArray[0] = one;
demoArray[1] = two;
demoArray[2] = three;

你应该声明它们。即

one = new JButton();.......

否则您将收到nullPointerException。 就可访问性而言,您应该对所拥有的内容感到满意。

答案 1 :(得分:1)

就访问而言,这应该有效。你应该在调用actionPerformed时遇到错误,因为你试图访问demoArray [3],但它只从0到2。

以下是一些工作代码,取自您自己的代码。有一些变化,我已经评论过了。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

// Extend JPanel so we can put the buttons somewhere
// Implement ActionListener so we can listen to them
public class Demo extends JPanel implements ActionListener {

    public JButton one;
    public JButton two;
    public JButton three;

    // This holds the same objects as above. You don't need both.
    public JButton demoArray[] = new JButton[3];

    // This is used to show the results
    public static void main(String[] args) {
        // Create our Demo
        Demo demo = new Demo();

        JFrame frame = new JFrame("Test");
        frame.add(demo);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    // Using uppercase for Class name and lower case for objects
    public Demo() {

        super();

        // Create our buttons            
        one = new JButton("one");
        two = new JButton("two");
        three = new JButton("three");

        // Put them in the array.
        // We could have just created them in the array directly.
        demoArray[0] = one;
        demoArray[1] = two;
        demoArray[2] = three;

        // Put the buttons inside this (the JPanel)
        // and listen to them
        for (JButton button : demoArray) {
            add(button);
            button.addActionListener(this);
        }
    }

    // What to do when we hear them
    @Override
    public void actionPerformed(ActionEvent e) {
        // There are only three buttons, not four
        // That is, demoArray[0], demoArray[1], 
        // and demoArray[2]
        for (int i = 0; i < 3; i++) {
            demoArray[i].setEnabled(false);
        }
    }
}