Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   for loop variables (http://www.programmingforums.org/showthread.php?t=13164)

emdiesse May 17th, 2007 5:48 PM

for loop variables
 
Hello. I have a need to create 81 buttons (named btn1...btn81).

Instead of typing out
:

JButton btn1        = new JButton("0")
JButton btn2        = new JButton("0")
...
JButton btn81        = new JButton("0")


is there a way I can use a for loop to do this
:

for(int i=0; i<=81; i++)
{
    JButton btni        = new JButton("0")
}

obviously this would probably not work for two reasons it would just make a button called btni 81 times probably, also i believe there would be scope issues?


How can I do this?
or do I just have to type them all out?

Thank you

andro May 17th, 2007 6:02 PM

Use an array of JButton.

Edit: Just read that wrong. If you _really must_ have them named btn1..btn81 instead of just accessing the correct index of the array then yes, you'll have to type them out.

emdiesse May 17th, 2007 6:17 PM

Ah no, thats nasty :( just a huge block of buttons.
also. I just i can't add them to the frame using a for loop either.

Oh, this means I have to put some effort in.

titaniumdecoy May 17th, 2007 7:13 PM

Why not just use an array?

emdiesse May 17th, 2007 8:18 PM

I didn't know that could be done with buttons.

Also, misread andros message. I didn't see the part saying if it was a must to have them named btn1 to btn81.

I have this now
:

JButton[][]btn = new JButton[9][9];
                for(int r=0;r<9; r++)
                {
                        for(int c=0;c<9; c++)
                        {
                                btn[r][c].setSize(25,25);
                                btn[r][c].setText("0");

                                pane.add(btn[r][c]);
                        }
                }


but when I run it I just get a blank frame.

PhilBon May 17th, 2007 9:11 PM

What is Pane? Variable? If so What kind? Are you updating the frame? I'm not used to working with Java frames and Panels but I'm guessing you have to make sure you update the frame somehow.

andro May 17th, 2007 9:32 PM

For starters, you need to add:

:

btn[r][c] = new JButton("0");

Before you go and try to add them.

emdiesse May 17th, 2007 9:38 PM

Quote:

Originally Posted by andro (Post 127974)
For starters, you need to add:

:

btn[r][c] = new JButton("0");

Before you go and try to add them.

Excellent!
You just solved my problem :D

ReggaetonKing May 17th, 2007 11:20 PM

Is a 2D array necessary for your JButtons? Why not just make a single JButton with a length of 81?


All times are GMT -5. The time now is 2:20 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC