Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Can I use a for loop to add anonymous ActionListener objects?

s3aJun 1 2011 — edited Jun 3 2011
I have a setListener() method that has the following inside:
for(int k = 0; k < buttons.length; k++)
{
    buttons[k].addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            g2.setColor(colors[k]);
        }
    });
}
I have a JButton array and a Color array and I was hoping I could add them quickly in one shot rather than manually adding an anonymous ActionListener 9 times (I have 9 components). It tells me I need to make k final for an inner class and when I tested it by removing the for loop and keeping k as a final integer, it works. Is there a medium such that I can achieve what I want more or less while respecting Java's syntax?

Any input would be greatly appreciated!
Thanks in advance!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 1 2011
Added on Jun 1 2011
26 comments
711 views