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?


4 Years
Discussion Span
Last Post by NormR1
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.