Esempio n. 1
0
    /**
     * Continues dragging a piece.
     *
     * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
     */
    @Override
    public void mouseDragged(MouseEvent e) {
      int x;
      int y;

      if (pieceBeingDragged == null) return;
      // Don't allow drag outside board boundaries
      int maxX = board.columnToX(board.getColumns() - 1);
      int maxY = board.rowToY(board.getRows() - 1);
      x = e.getX() - board.getCellWidth() / 2;
      if (x < 0) {
        x = 0;
      } else {
        if (x > maxX) x = maxX;
      }
      y = e.getY() - board.getCellHeight() / 2;
      if (y < 0) {
        y = 0;
      } else {
        if (y > maxY) y = maxY;
      }
      pieceBeingDragged.x = x;
      pieceBeingDragged.y = y;
      // Track mouse movement
      pieceBeingDragged.setChanged();
      pieceBeingDragged.notifyObservers();
    }
Esempio n. 2
0
 /**
  * When the mouse button is pressed over a draggable piece, begins the dragging process. Only
  * one piece can be dragged at a time.
  *
  * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
  */
 @Override
 public void mousePressed(MouseEvent e) {
   board.setSelectedSquare(board.yToRow(e.getY()), board.xToColumn(e.getX()));
   Piece chosenPiece = board.findPiece(e.getX(), e.getY());
   if (chosenPiece == null) {
     return;
   }
   if (chosenPiece.isSelectable()) {
     board.setSelectedPiece(chosenPiece);
   }
   if (pieceBeingDragged != null) {
     return; // can only drag one piece at a time
   }
   if (!chosenPiece.draggable) {
     return;
   }
   pieceBeingDragged = chosenPiece;
   board = pieceBeingDragged.board;
   pieceBeingDragged.moving = true;
   board.moveToTop(pieceBeingDragged);
 }
Esempio n. 3
0
    /**
     * Terminates the drag process, putting the dragged piece in the nearest square.
     *
     * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
     */
    @Override
    public void mouseReleased(MouseEvent e) {
      if (pieceBeingDragged == null) return;
      Rectangle oldRect = pieceBeingDragged.getRectangle();
      Rectangle newRect = oldRect;
      int newRow = board.yToRow(pieceBeingDragged.y + board.getCellHeight() / 2);
      int newColumn = board.xToColumn(pieceBeingDragged.x + board.getCellWidth() / 2);

      if (pieceBeingDragged.canMoveTo(newRow, newColumn)) {
        pieceBeingDragged.changePosition(newRow, newColumn);
      }
      pieceBeingDragged.moving = false;
      newRect = pieceBeingDragged.getRectangle();
      pieceBeingDragged.redraw(pieceBeingDragged.enlarge(oldRect.union(newRect)));
      board.dragEvent.reportEvent(pieceBeingDragged);
      pieceBeingDragged = null;
    }