[英]Java - How to allow all methods of a class to access an array initialized in constructor?
我很想知道如何在一个类中声明和初始化一个 JButton 数组,以便同一个类的构造函数和方法都可以访问这个数组。
目前,我在类定义的开头声明了 JButton 和数组,并在类构造函数中初始化了数组。 但是,这不允许类的其余方法访问数组的变量。
非常感谢您的帮助!
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);
}
}
}
在类作用域中声明并在构造函数中初始化的变量应该在类中的任何地方都可以访问。
如:
private/public <Class> <object>;
应该足够了,如果您需要进一步的帮助,则需要查看一些代码。
[编辑] 您发布的内容应该可以正常工作,但在此之前
demoArray[0] = one;
demoArray[1] = two;
demoArray[2] = three;
你应该声明它们。 IE
one = new JButton();.......
否则你会得到一个 nullPointerException。 就可访问性而言,您应该对自己拥有的东西感到满意。
就访问而言,这应该有效。 当 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.