I am working on a project where i need to dynamically count how many buttons need to be added to a certain panel. Each button press has to change a variable in the parent class and then to excute generation of a child panel which also dynamically generates buttons. my problem is that even though I am able to generate the buttons, and add them to the layout, I dont know how to change their individual actionlisteners. The code I have right now is this:

 private void PopulateBooks() {
        for (int i = 0; i < 14; i++) {
            books.add(new JButton("Book " + GetRoman(i)));
            books.get(i).addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    currentBook = i;
                }
            });
        }
    }

currentBooks is an integer in the class to which PopulateBooks() belongs to. The problem is that i is local to the for loop and netbeans is throwing an error. is there any way of doing this? I thought of manually generate the seperate listeners by passing actual numbers using switch statement, but then the switch statement's cases will need to be dynamic. Any ideas?

Thanks!
Sid

Please post the full text of the compiler's error message.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.