Reputation: 59
I have a question about "linking" a 2D array of a class to JButttons. I'm having a similar problem to this previously-asked question and found the solution to be very helpful. I need to create a 4x4 board of JButtons with pictures. I'm using a Square class to represent each of the grid squares and they should each be JButtons. I initialised it in my Board class through private Square[][] square = new Square[4][4];
However, I don't understand how to add an image to a JButton when the class is different. I originally did it by square[i][j] = new JButton(p);
where p is the object name of the image I'm using but it throws an error: "JButton cannot be converted to Square".
How would I go about avoiding this error? Also, I don't want to create a 2D array of JButtons.
My Square class is basically:
public class Square extends JButton
{
private int xNum;
private int yNum;
public Square(int xNum, int yNum) {
this.xNum = xNum;
this.yNum = yNum;
}
// and then a few get and set methods...
}
Upvotes: 1
Views: 73
Reputation: 43
It would be nice to see the code for you object square but im assuming that you can just add a private variable JButton into your square class, you can then create getters and setters. Now when you loop through your for loop and initialize your squares, you can do
square[i][j] = new square();
square[i][j].setJButton(new JButton(p));
and whenever you need to access the JButton call
square[i][j].getJButton();
Hope this helps, if I understood your question wrong please comment and I will try to get back to you quickly.
Upvotes: 1