Skip to main content
gamedev.net
🔒 Locked

[java] Jbutton arrays?

Started by DefCom Nov 30, 2002 at 7:14 AM 2 replies 300+ views
Original Post
DefCom
DefCom
I am using Jbuttons to create a floor plan so that the user can click on the appropriate room and the program will execute appropriatly. I am currently using individual JButtons which work just fine, but i wish to use an array for the JButtons, my code looks a little like this: JButton BFloorPlan[] = new JButton[12]; BFloorPlan[0].setIcon(Image01); BFloorPlan[0].setBounds(0,0,64,64); pane.add(BFloorPlan[0]); It compile with 0 errors but when i execute the function the program hangs as though i have written past the end of the array or the image is not available, both not true. Any help or advise would be much appriciated, thanks
neonoblivion
neonoblivion
I think you have to add after:
JButton BFloorPlan[] = new JButton[12];

some code which is like:
for(int index=0;index<12;index++)
BFloorPlan[index] = new JButton(/*whatever init params you want...*/);

that should do it. You aren't actualy instantiating a class of JButton with your code as-is.
Klaus

//edit:fixed the code



[edited by - neonoblivion on November 30, 2002 8:26:16 AM]
DefCom
DefCom
Thanks for the responce

I didn''t try it inside a loop, but i did try individual constructors, it just threw up errors.
Petr Stedry
Petr Stedry
Hi DefCom,

just to be sure you do know what your code means ...
quote:
Original post by DefCom
JButton BFloorPlan[] = new JButton[12];


This line says: "There will be an array of JButton objects, that will be 12 elements long" or better "There will be an array that can accomodate up to 12 JButton (or simillar - read subclasses) objects".
So you told the computer that an array will exist, but didn't say a word about objects that it contains. Understand?

P.S.:
Try to avoid "magic numbers" - use constants instead! The program gets a lot more readable .
For example:
public static final int DEFAULT_FLOOR_PLAN_SIZE = 12;
...
JButton BFloorPlan[] = new JButton[DEFAULT_FLOOR_PLAN_SIZE];
is much more fun to read just BTW

have fun ...

Petr Stedry

[edited by - Petr Stedry on November 30, 2002 10:31:20 AM]
Petr Stedry

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.