Reputation: 343
So the issue here is fairly simple; I have a "for"- loop that doesn't work properly. The "for"-loop is situated at the end of the second class, in the "generateBlock()" method. This "for"-loop is supposed to change the text of the labels from the array labels[] to "Text changed".
The problem I am encountering is that, if I set "for (i = 0; i < 12; i++);", I get an outofbounds error, and if I set "for (i = 0; i < 11; i++);", I don't have that outofbounds error. This is pretty strange since the index of the array actually consists of 0 to 11. But well, that is not even the main problem.
The main problem is that if I set "for (i = 0; i < 11; i++);", only the last labels[i] (thus labels[11]) has its text changed to "Text changed" while the other labels[i] all stay the same and thus unchanged.
This is pretty weird since i < 11 so labels[11] should be the only one to remain unchanged, but in this case it is apparently reversed and I don't know why. I also don't know why I get that outofbounds error if I set i < 12, since I'm pretty sure that the index of the array consists of 0 to 11.
If I manually set "coloredWords.labels[0].setText("Text changed");" and then copy paste this line for all the other values it does work though.
public class ColoredWordsExperiment {
JFrame frame;
JLabel[] labels;
ButtonHandler buttonHandler;
int i;
ColoredWordsExperiment(){
frame = new JFrame ();
button1 = new JButton("Matching");
labels = new JLabel[12];
for (i = 0; i < 12; i++) {
labels[i] = new JLabel("label");
labelContainer.add(labels[i]);
}
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")) {
generateBlock();
}
}
public void generateBlock(){
int i = 0;
for (i = 0; i < 11; i++); {
coloredWords.labels[i].setText("Text changed");
}
}
}
Upvotes: 0
Views: 64
Reputation: 433
First your for loop is terminating as you are doing
for( i = 0 ; i < 11 ; i ++); // replace this line with
for( i =0; i <11; i++){
//your logic }
Second thing if you want to change your last label[11] change to "Text Changed", put tis condition inside the for loop -
If( i ==11){
coloreWords.labels[i].set text("Text Changed");
} But you should just double check your array index,if it is really a 11 index array than your code should be run till i<12.
Upvotes: 1
Reputation: 68715
Your for
loop is not executed even once because you have terminated it with a semicolon(;
). Remove the semicolon after the for loop:
for (i = 0; i < 11; i++); {
should be
for (i = 0; i < 11; i++) {
Upvotes: 3