File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Question about a 2D array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question about a 2D array" Watch "Question about a 2D array" New topic

Question about a 2D array

Ryan Davey

Joined: Nov 13, 2008
Posts: 2
Hey there, I'm a beginner to java, of course.

Through using google to figure out problems i've noticed this site a handful to times and I've found it to be very helpful, so i figured i would register.

On to my question.

I'm trying to initialize 3 x 3 array of JPanels with nested enhanced for loops, but it's not working.

Edit: sorry for the vagueness. It doesn't seem to be working because i'm getting a null pointer exception in another part of my program. Which means that the loop doesn't even seem to be going anywhere. each panel is just ending up "null" after the loop. I'll debug this and try to see what exactly it is doing and come back with another edit or a reply if i figure it out. Sorry i didn't do this before, i only had about 5 minutes left in the class i was in.

This code works, but it looks terrible, haha, and i'm sure it's bad practice, but i'm new to programming in general, not just java. I know there's probably a more concise way to do this with for loops.

[ November 13, 2008: Message edited by: Ryan D. ]
Henry Wong

Joined: Sep 28, 2004
Posts: 20517

The panel variable is a looping variable -- it is assigned to the value of each element of the array. Setting it doesn't set the array. Setting it just changes the looping variable.

To change the array itself, you need to assign the array. And it is easier to use the other for loop.

[ November 13, 2008: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ryan Davey

Joined: Nov 13, 2008
Posts: 2
This makes sense. Thanks for the help.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Note that

is legal, and would prevent you from making this mistake. Really, they should have made the loop variable final by default, IMO. But using "final" there is a good habit to get into.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Question about a 2D array
It's not a secret anymore!