1

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...
}
bachtick
  • 49
  • 6

1 Answers1

1

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.

Wolfang
  • 23
  • 1
  • 9
  • 2
    Also when initializing objects you cant initialize it to be another object unless the other object is a sub part of it. There's a whole entire topic on it called polymorphism, it is very useful in bigger projects and if you continue with Java you are bound to run into a situation where you need it. In your case I really don't think you will need to use this technique. – Wolfang Mar 09 '21 at 19:36
  • Thank you for your reply! If I've extended the Square class to JButton, would I still have to add the private variable of JButton? – bachtick Mar 10 '21 at 12:17
  • I've also given the original code for my square class, and I think I've shown the code for my square object in the post. I tried your solution but I get the error "cannot find symbol in `square[i][j].setJButton(new JButton(p));` "... – bachtick Mar 10 '21 at 12:38
  • So instead of extending JButton, id recommend for what you need, underneath your private int xNum and yNum add private JButton jb; Then you have your getters and setters for jb(or whatever you named it) and then it should work fine. – Wolfang Mar 11 '21 at 13:06