0

I'm trying to move a piece from one square in a grid to another by clicking first on the piece and then clicking on the square to move it too.

How can I save the location of the first icon, and then swap it with the second?

At the moment I'm looking at this code which simply moves the piece one square left:

public void actionPerformed(ActionEvent e)  
{
for ( x=0; x<8; x++)
        for( y=0; y<8; y++) {
        if(e.getSource() == board[x][y])
        ((ChessSquare)e.getSource()).swap(board[x][y-1]);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2079483
  • 135
  • 2
  • 3
  • 12

2 Answers2

1
  • Store a flag indicating whether this is a 'drag' or 'drop'1.
  • If 'drag' store the original co-ordinates and change the flag to 'drop'.
  • If 'drop' read the co-ordinates of the source, use them as you will and set the flag back to 'drag'.

  1. By that I mean something like declaring a boolean drag and setting it true/false as needed.

..best place to store the coordinates?

I'd use 2 int attributes, though if you wanted to misuse a Dimension object, just one could store both x & y co-ords.

..No, scrap that. Using the client properties as indicated by mKorbel seems a lot more 'neat'.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0
  • We'll need a Boolean flag which will keep track of 'click'
  • if flag = false it's first click otherwise it's second click (this is where we'll perform swap).

    public void actionPerformed(ActionEvent e)  
    {
        int xPos1,xPos2,yPos1,yPos2;
        if(!flag)
        {
          for ( x=0; x<8; x++)
          {
              for( y=0; y<8; y++) 
              {
                if(e.getSource() == board[x][y])
                {
                  xPos1 = x; // Source icon cordinates.
                  yPos2 = y;
                  break;
                }
              }
          }
          flag = true;
        }
        else
        {
          for ( x=0; x<8; x++)
          {
            for( y=0; y<8; y++) 
            {
              if(e.getSource() == board[x][y])
              {
                xPos2 = x;  // Target icon cordinates.
                yPos2 = y;
                break;
              }
            }
          }
    
          // Swapping code add your version of this swapping code here.
          // Swap source with target.
          Icon temp = board[xPos1][yPos1]
          board[xPos1][yPos1] = board[xPos2][yPos2];
          board[xPos2][yPos2] = temp;          
          // ----------------- End Swap----------------  
    
          flag = false; // ready for next swap operation.
      }   
    

    }

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59