[英]Why can't this class find this array?
我有一个在第一个类( ColoredWordsExperiment )中工作的数组,而第二个类( ButtonHandler )无法找到它。
奇怪的是,如果我在ButtonHandler类,替代coloredWords.labels [I]或让我们说“coloredWords.labels [1]”为根本coloredWords.labels1,而在第I类声明JLabel labels1 = new JLabel;
有用。
基本上这就是我最初所拥有的,但是由于我有12个标签,所以我决定改用数组。 现在的问题是,ButtonHandler类无法找到变量“ coloredWords.labels [i]”。
这是代码(我忽略了不重要的内容,否则代码会很长):
public class ColoredWordsExperiment {
ButtonHandler buttonHandler;
ColoredWordsExperiment(){
JLabel[] labels = new JLabel[12];
for (i = 0; i < 12; i++) {
labels[i] = new JLabel("Press Button");
labels[i].setPreferredSize(new Dimension(90,40));
labels[i].setOpaque(true);
labels[i].setBackground(Color.white);
labels[i].setHorizontalAlignment(SwingConstants.CENTER);
labelContainer.add(labels[i]);
}
button1 = new JButton("Matching");
buttonHandler = new ButtonHandler(this);
button1.addActionListener(buttonHandler);
}
public static void main(String[] arg) {
new ColoredWordsExperiment();
}
}
-
class ButtonHandler implements ActionListener {
ColoredWordsExperiment coloredWords;
public ButtonHandler(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
@Override
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("Matching")) {
for (i = 0; i < 12; i++) {
coloredWords.labels[i].setText("Text changed");
}
}
}
JLabel[] labels
是在您的ColoredWordsExperiment
类的构造函数中声明的变量。 将其作为类中的字段移动,并在类构造函数中对其进行初始化:
public class ColoredWordsExperiment {
ButtonHandler buttonHandler;
//it should be declared here
JLabel[] labels;
ColoredWordsExperiment() {
//this is a variable inside the class constructor
//JLabel[] labels = new JLabel[12];
//this line initializes the labels field
labels = new JLabel[12];
// rest of your code...
}
}
同样,您应该声明一个getter方法来获取labels
变量内的JLabel
之一,而不是直接访问此变量。 这将使您的代码更整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.