0

Hey im new to java in grade 10 and I came through a small problem. I'm creating the game 4 pics on word and I can't seem to put a different image in each square of my grid.

Here is the grid

The decleration:

int row = 4;
int col = 4;
JButton a[] = new JButton [row * col];  

And here's the array:

card4 = new Panel ();
Panel g = new Panel (new GridLayout (row, col));
for (int i = 0 ; i < a.length ; i++)
{
   a[i] = new JButton ("Hi");
   a[i].setPreferredSize (new Dimension (50,50));
   g.add (a[i]);
}

How would I call out each individual button on the grid and assign a different image to it?

Maximilian Gerhardt
  • 5,188
  • 3
  • 28
  • 61

1 Answers1

1

When you run new JButton("Hi"), you are invoking (one of) the constructor(s) for the class. JButton has several different constructors taking different parameters. One of those constructors is JButton(String text, Icon icon), that allows specifying an Icon to draw in the button. So, first you would have to create an Icon and then create the button using it, like:

Icon icon = new ImageIcon("name/of/file/containing/icon/image");
a[i] = new JButton("Button Text", icon);

If you only want an icon and no text, then just use:

Icon icon = new ImageIcon("name/of/file/containing/icon/image");
a[i] = new JButton(icon);

The file containing the image can be a jpg, png, gif. Look in Java Tutorial on now to use images and controls.

DBug
  • 2,502
  • 1
  • 12
  • 25