0

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".

2
Contributors
6
Replies
7
Views
5 Years
Discussion Span
Last Post by NormR1
0

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
0

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

0

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.

Edited by NormR1

This question has already been answered. 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.