[英]Why can't this class find this array?
I have an array which works in the first class ( ColoredWordsExperiment ), while the second class, ( ButtonHandler ), cannot find it. 我有一个在第一个类( ColoredWordsExperiment )中工作的数组,而第二个类( ButtonHandler )无法找到它。
The strange thing is that if I, in the ButtonHandler class, substitute coloredWords.labels[i] or let's say "coloredWords.labels[1]" for simply coloredWords.labels1 , while in the first class I declare JLabel labels1 = new JLabel;
奇怪的是,如果我在ButtonHandler类,替代coloredWords.labels [I]或让我们说“coloredWords.labels [1]”为根本coloredWords.labels1,而在第I类声明
JLabel labels1 = new JLabel;
it works. 有用。
That's basically what I initially had but since I have 12 labels I decided to use an array instead. 基本上这就是我最初所拥有的,但是由于我有12个标签,所以我决定改用数组。 The problem now is that the class ButtonHandler cannot find the variable "coloredWords.labels[i]".
现在的问题是,ButtonHandler类无法找到变量“ coloredWords.labels [i]”。
This is the code (I left out unimportant stuff otherwise the code would be quite long): 这是代码(我忽略了不重要的内容,否则代码会很长):
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
is a variable declared inside the constructor of your ColoredWordsExperiment
class. JLabel[] labels
是在您的ColoredWordsExperiment
类的构造函数中声明的变量。 Move this as a field in the class and initialize it in your class constructor: 将其作为类中的字段移动,并在类构造函数中对其进行初始化:
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...
}
}
Also, you should declare a getter method to obtain one of the JLabel
s inside the labels
variable instead of using a direct access to this variable. 同样,您应该声明一个getter方法来获取
labels
变量内的JLabel
之一,而不是直接访问此变量。 This will make your code cleaner. 这将使您的代码更整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.