Trying to write a for loop to insert buttons into the array.

This is the code to create an array that can hold 7 values:

JButton[] buttons = new JButton[7];
String[] buttonText = {"Circle", "Square", "Oval", "Smiley", "Swirl", "Start", "Stop"};

This is the for loop I'm not sure about to fill the array:

int i = 0;
for (int buttons[] = 0; buttons.length(); buttons[i++]) {
    JButton addButton = new JButton(buttonText);
}

And this is the foreach loop which accesses each element in the array and adds a listener and adds the buttons to the panel:

for (JButton button : buttons) {
    button.addActionListener (listener);
    controlPanel.add (button);
}

It comes up with a compile error saying buttons[i++] "is not a statement".

Recommended Answers

All 6 Replies

Not sure why you are using array notation (with []s) in a for statement.
Normally an int value is used.

Take a look at the tutorial: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

The whole project could be done in one loop:
begin loop
create button
add listener to button
add button to container
end loop

Ok, so I changed the for loop to:

for (int i = 0; i < buttons.length(); i++) {
    JButton addButton = new JButton(buttonText);
}

And I get the error:

[line : 1]
cannot find symbol
symbol  : method length()
location: class javax.swing.JButton[]

And the error:

[line : 2]
cannot find symbol
symbol  : constructor JButton(java.lang.String[])
location: class javax.swing.JButton

How would I go about doing it this way?
begin loop
create button
add listener to button
add button to container
end loop

Arrays don't have methods. The ending ()s are how method calls are coded.
length is a field/property of an array that has the length of the array.
See the tutorial: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

cannot find symbol : constructor JButton(java.lang.String[])

The JButton class does not have a constructor that takes a String array as an arg.
You need to index into the array to get a single String for the constructor.

How would I go about indexing into the array?

indexing into the array

Something like this:
theArray[theIndex]

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.