I am using a loop to add some listeners to 5 items. I am getting an OOB error and I know why, but I do not know how to fix it.
Here is the code:
int i;//class variable
...
for(i = 0; i < fonts.length; i++){//both fonts and fontItemList are the same size: 5
fontItemList[i] = new JMenuItem(fonts[i]);
fontItemList[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editor.setFont(new Font(fonts[i], 0, 12));//error occurs here
}
});
}
The reason why I am getting the error is because the listener is only executed when the user clicks on the item, however, by that time, i = 5, which is the size of my list, resulting in OOB error.
What this code is supposed to do is create 5 JMenuItem objects that will change the font of when the corresponding JMenuItem is pressed.