Mouse Movement
Hi,
This is my first post so I hope it is in the right location, I have had a browse of the forum but cannot seem to find the answer to my question.
I am creating a checkers game and am using a layeredPan which has a grid layout applied to it. I have created my pieces from images and can move them about but I am having great difficulty in stopping users from moving the pieces out of the window. I have tried to use a check method on my mouse movement but it only partially works the mouse code is posted below to see if anyone can help me.
public void mousePressed(MouseEvent buttonPress)
{
int squareX, squareY;
piece = null;
int buttonX = buttonPress.getX();
int buttonY = buttonPress.getY();
bX = buttonX;
bY = buttonY;
Component boardC = board.findComponentAt(buttonX,
buttonY);
if(boardC instanceof JPanel)
{
return;
}
square = (JComponent)boardC.getParent();
xMovement = (square.getX() - buttonX);
yMovement = (square.getY() - buttonY);
piece = (JLabel)boardC;
piece.setLocation((xMovement + buttonX), (yMovement + buttonY));
lPane.add(piece, JLayeredPane.DRAG_LAYER);
startX = (square.getX()/100);
startY = (square.getY()/100);
}
/*
** Move the piece around
*/
public void mouseDragged(MouseEvent pieceDragged)
{
int dragX, dragY;
if(piece == null)
{
return;
}
piece.setVisible(false);
dragX = pieceDragged.getX();
dragY = pieceDragged.getY();
totalX = dragX + xMovement;
totalY = dragY + yMovement;
if(totalX>=0 && totalX<=800 && totalY>=0 && totalY<=800)
{
piece.setLocation((dragX + xMovement), (dragY + yMovement));
}
else
{
piece.setLocation(bX, bY);
square.add(piece);
System.out.println("you must move pieces with the board area");
piece.setVisible(true);
return;
}
piece.setVisible(true);
}
/*
** Drop the piece onto the board
*/
public void mouseReleased(MouseEvent pieceDropped)
{
int dropX, dropY, squareX, squareY;
if(piece == null)
{
return;
}
if(totalX<0 || totalX>800 || totalY<0 || totalY>800)
{
square.add(piece);
return;
}
Please feel free to look at and modify the code but do not take credit for it if you do use it on any manner.

