Deep copies of an array of 2d objects

how can I make on a button click a new deep copy of a 2-dimensional array?

Basically I created a game board with buttons. The game is called sokoban and it is a puzzle. The player moves from one button to another using the arrow keys on the fixed map (8x8 buttons). I want to implement a cancellation function. So I thought I would just create a deep copy of the JButton array before each move and store it on the stack. So when I hit the cancel button it calls the pop function from my stack. The problem is that I need to declare and initialize another JButton [] [] where I can save the playing field until every turn. Since I need infinite possible moves as well as undo, this seems impossible to me. I cannot declare and initialize infite different JButton [] [] arrays. Any idea on how I can solve this?

How to copy an array of 2d objects:

    JButton[][] tempArray = new JButton[jbArray.length][jbArray[0].length];

    for (int i = 0; i < getJbArray().length; i++) {
        for (int j=0;j<getJbArray()[0].length;j++) {
            tempArray[i][j]=jbArray[i][j];
        }
    } 

    movesStack.push(tempArray);

      

+3


source to share


2 answers


Unfortunately, you cannot clone swing components at all as they do not implement the Cloneable interface. As I see it, you have two options:

  • Create a new JButton inside a double loop and copy any properties (like alignment, color, etc.) you set into the new JButton

  • Write your own class that extends JButton and implements the Cloneable interface



The first way is a bit of a hack and not very reliable or reusable. The second way is much better practice. In this case, you will need to determine how the deep copy is to be performed and make sure all relevant properties are copied.

+2


source


You have the right idea. You're not quite deep enough.

    public JButton[][] copy(JButton[][] jbArray) {
        JButton[][] tempArray = new JButton[jbArray.length][jbArray[0].length];

        for (int i = 0; i < jbArray.length; i++) {
            for (int j = 0; j < jbArray[0].length; j++) {
                tempArray[i][j] = new JButton(jbArray[i][j].getText());
            }
        }

        return tempArray;
    }

      



Instead of copying the JButtons, you should have a model that you use to install the JButtons. Maybe an array ModelClass[][]

?

0


source







All Articles