• 0

[Java] Concat Help


Question

JButton cb0 = new JButton ();
JButton cb1 = new JButton ();
JButton cb2 = new JButton ();

String array1 = {"yes", "no", "maybe"};

What I'm trying to do over here is add the strings from array1 into the buttons cb0, cb1, and cb2, such that cb0's text will be "yes", cb1's text "no" and so on. How can I do this using a for loop?

I have a very vague idea on how to do this. I can't figure out how to go to the next button using i. My attempt at a concat is shown below. As an example, the first time it would read cb0.setText (array1 [0]);, the next time cb1.setText (array1 [1]);

for (int i = 0; i < 3; i++)
{
    cb + i.setText (array1 [i]);
}

Please let me know if I didn't explain it clearly.

-0

Link to comment
Share on other sites

8 answers to this question

Recommended Posts

  • 0

Sorry, i should have said around the cb+i, my apologies.

for(int i=0;i<3;i++)
{

      (cb+i).setText(array1[i]);

}

The reason for putting the brackets there is because cb0, or cb1 or cb2 is the object you are calling the setText() method on. Hope that makes sense

Link to comment
Share on other sites

  • 0

You can't access variable names that way. If you want to do multiple variables like that, use an array.

JButton[] cb = new JButton[3];
for(int i=0;i<3;i++)
{
     cb[i] = new JButton(array[i]);
}

Also makes it easier on you to declare.

Edited by kjordan2001
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.