1

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.

1
  • Why is i a class variable, and what is editor? Does the error occur for the first item in the list or only after five of the items have been clicked on? Commented Nov 28, 2015 at 2:08

1 Answer 1

2

You should not use the class variable (field) i here as it will be the same for every listener. What you actually need is to capture the font:

for(int i=0 ; i<fonts.length; i++) {
    final String font = fonts[i];
    fontItemList[i] = new JMenuItem(font);  
    fontItemList[i].addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e){
            editor.setFont(new Font(font, 0, 12));
        }

    });
}

This way every listener will get its own font. In anonymous class you can capture the final local variable (since Java-8 you may omit the final keyword if you don't actually change the variable). And within the object of anonymous class it will always have the same value which was during the object creation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.