0

Hey everyone,

I want to add action listeners to JButtons that were created dynamically by an ArrayList. Here is the code for the button creation.

numOfCourse = 6;

courseBtnArray.add(new JButton("Course 1"));
        gbc.gridx = 2;
        for (int i = 0; i < numOfCourses; i++) {
            gbc.gridy++;
            add(courseBtnArray.get(i), gbc);
            courseBtnArray.add(new JButton("Course " + (i + 2)));
        }
        gbc.gridy++;
        add(courseBtnArray.get(courseBtnArray.size() - 1), gbc);
        System.out.println("the size of the textbox arraylist is:" + courseBtnArray.size());

So how can i refer to these buttons because they themseleves don't have a referance.
Here is one way: courseBtnArray.get(1).addActionListener(clickListener);. This works, but the user does have the ability to add a greater number of courses than 6. So this way any buttons great than index 5 would be useless.
So what can I do?

Thanks

3
Contributors
2
Replies
12
Views
3 Years
Discussion Span
Last Post by mKorbel
0

This works, but the user does have the ability to add a greater number of courses than 6. So this way any buttons great than index 5 would be useless.

I have .... no idea what you're trying to say there. (one of) the advantages of Lists and Collections is that, unlike with using arrays, you don't have to know up front the number of elements in it.
why wouldn't they be able to have their own actions? but on the other hand, what kind of screen would it be, that might have an infinite number of buttons on it? because that is a bit how you describe it.

0

agreed with @stultuske, another points, depends of

  • JButtons arrays is created once time or dynamically on runtime

  • not sure if GBC (this ways) works correctly (from posted codesnipped), maybe use GridLsyout

  • no idea whats courseBtnArray.add(new JButton("Course 1")); and courseBtnArray.add(new JButton("Course " + (i + 2)));, why JButtons are added two different ways to one contianer, or am I wrong

  • is courseBtnArray the JPanel

Edited by mKorbel

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.