Search code examples
javajbutton

How do I make a JButton move to an empty tile?


So I got an assignment in Java to make an 8 piece puzzle, and I chose to use JButtons for tiles (don't know if that's even possible). I've got the buttons to appear in a random order when starting it, but I have no idea how to make the tiles able to move when you click on them. So I'm wondering if someone could just point me in the right direction? I've come to conclusion that I need to use Actionlistners and saw an old user here getting tip of doing Actionlistners on every button, but I am having trouble with knowing what to writ, and do I put this in another class?

Any help is very much appreciated!

The product so far:

Embedded a picture of the product so far


Solution

  • To make it easier, you could add ninth button which is transparent and not clickable. Every but should has his id, which would also tell hes position.

    11 12 13
    21 22 22
    31 32 33
    

    So for every button you already assign his random number. Now just like you use actionlistners to detect which button is clicked. And when is clicked you check if button that is neighbor is transparent. If transparent you would swap there values, one would become visible,other transparent and not clickable.

    To get button neighbors you would use + and - operations.

    int leftNeighbour = id - 1;
    int rightNeighbour = id + 1;
    int topNeighbour = id - 10;
    int bottomtNeighbour = id + 10;
    

    I assume that all buttons are saved in an array so you just go like this:

    for(Button tempButton : Buttons)
    {
       if(leftNeighbour > 0 && leftNeighbour == tempButton.id) //we check first if button id is OK, then we compere it with tempButtons id
       {
          int tempButtonValue = tempButton.value;
          tempButton.value = currentButton.value;
          currentButton.value = tempButtonValue ;
          makeButtonTransparent(tempButton);
          break; //we found over neighbor so we can stop for loop
       }
       //then you check conditions for other neighbor id's. Butt first condition is allays different
    }
    

    I hope that I didn't make it over complicated, but this is idea that I got in few minutes, when I was thinking how I would make it with buttons. There is probably some better way to set ID's to buttons, and check if they are neighbors.