-
JPanel "for" loops Help
So this is what i want to do. I want to create 64 JPanel "panes" with a for loop and set each to a different color. the output i want is a 8x8 screen of random colors. i don't know how to create 64 panes inside a for loop. any help? i used the '[]' because i saw it another program, but i have no idea what it means.
i have this so far...
Code:
import javax.swing.*;
import java.awt.*;
import java.util.Random;
class Checkerboard2
{
public static void main(String [] args)
{
JFrame theGUI = new JFrame();
theGUI.setTitle("Fourth GUI Program");
theGUI.setSize(300, 200);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Random generator = new Random();
int counter;
for(counter = 0; counter <= 64; counter++)
{
Color aColor = new Color(generator.nextInt(),generator.nextInt(),generator.nextInt());
JPanel pane[counter] = new JPanel();
pane[counter].setBackground(aColor);
}
Container pane = theGUI.getContentPane();
Thanks!
-
JPanel [] pane is assigned 64 JPanels but where is it actually declared?
-
Did you try running this code?
Code:
JPanel pane[counter] = new JPanel();
pane[counter].setBackground(aColor);
That will provide a compiler error. As al_Marshy said you need to declare the array using JPanel[] pane (as well as a new declaration) in the earlier part of the code. You can then assign elements to that array in your loop.
Here is some info on declaring arrays: Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)
-
Well I'm not that great at Java yet. i dont quite understand arrays. Could you explain how i could declare the "pane" object 64 times with a loop?
-
how to declare an array:
int [] myIntArray=new int [64];
JPanel [] pane =new JPanel[64];
and do please read Zack's link so in future you are not 'coding in the dark'
-
thanks. i got the array to compile. however, how do i make the code set the background of each pane, the add the panes to the JFrame?
-
You have already been given a link to a tutorial on the Oracle site. Don't you think you should scout around and see what other tutorials that site has to offer?
Believe me, learning systematically is much more fun than having to ask a question about each and every step of your process.
db
-
OK! Ill try and see if i can do it on my own! thanks everyone!