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...
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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?
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)); "...
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.