1

Im trying to make some buttons in a for each loop but i cant figure out how its right. Does it even Work ?

        String[] myButtons = {"Label","Checkbox","CheckboxGroup", "Textfield", "TextArea","Choice", "List", "Scrollbar", "ScrolPane", "Ende"};

    for (String buttonName : myButtons) {
        Button buttonName = new Button( buttonName );
    }
2
  • 1
    You will need to more clearly state what you are trying to do and what the problem is. Commented Mar 13, 2015 at 17:59
  • You can add your button to a JPanel or JFrame by invoking the .add() method. Commented Mar 13, 2015 at 18:07

2 Answers 2

2

Sure, if you don't try to reuse buttonName, then you'll be able to compile and create some buttons:

for (String buttonName : myButtons) {
    Button button = new Button( buttonName ); // right here!
}

But you're not doing anything with them. Maybe you want to add them to a frame?

for (String buttonName : myButtons) {
    Button button = new Button( buttonName );
    frame.add(button);
}

And are you sure you don't want to use JButton?

Sign up to request clarification or add additional context in comments.

Comments

2

It looks like you're recreating the Button object with each pass. You only have a list of String names when you also need to instantiate a list of actual Button objects. Try this:

String[] buttonNames = {"One", "Two", "Three", "Four", "Five"};
Button[] buttons = new Button[buttonNames.length];
for (int i = 0; i < buttons.length; i++) {
   buttons[i] = new Button(buttonNames[i]);
}

Depending on what your Button object is, you could also include an anonymous function inside the for loop that would bind each button created to an event listener.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.