School Java Project Chinese Chess (6)

Moving pieces with a mouse

...
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

...

class CChessPanel extends JPanel implements MouseListener {
static int orgX = 83, orgY = 83, side = 67;
private CChessBoard brd; CChessPanel(CChessBoard brd) {
this.brd = brd;
addMouseListener(this);
}
public void mousePressed(MouseEvent me) {}
public void mouseReleased(MouseEvent me) {}
public void mouseClicked(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}

...
}
  public void mousePressed(MouseEvent me) {
Point mouseTip = me.getPoint();
System.out.println(mouseTip);

}
java.awt.Point[x=153,y=151]
java.awt.Point[x=82,y=76]
java.awt.Point[x=221,y=155]
java.awt.Point[x=285,y=154]
  public void mousePressed(MouseEvent me) {
Point mouseTip = me.getPoint();
System.out.println("mousePressed at (" + mouseTip.x + ", " + mouseTip.y + ")");

}
public void mouseReleased(MouseEvent me) {
Point mouseTip = me.getPoint();
System.out.println("mouseReleased at (" + mouseTip.x + ", " + mouseTip.y + ")");

}
mousePressed at (150, 153)
mouseReleased at (217, 220)
mousePressed at (7, 6)
mouseReleased at (84, 83)
private Point xyToColRow(Point xy) {
return new Point((xy.x - orgX + side/2)/side, (xy.y - orgY + side/2)/side);
}
class XiangqiPanel extends JPanel implements MouseListener {
...
private Point fromColRow;
...
public void mousePressed(MouseEvent me) {
fromColRow = xyToColRow(me.getPoint());
}
public void mouseReleased(MouseEvent me) {
if (fromColRow == null) return;
Point toColRow = xyToColRow(me.getPoint());
if (brd.validMove(fromColRow.x, fromColRow.y, toColRow.x, toColRow.y)) {
brd.movePiece(fromColRow.x, fromColRow.y, toColRow.x, toColRow.y);
System.out.println(brd);

repaint(); // redraw the updated game board
}

...
}
  0 1 2 3 4 5 6 7 8
0 R N B G K G B N R
1 . . . . . . . . .
2 . C . . . . . C .
3 P . P . P . P . P
4 . . . . . . . . .
5 . . . . . . . . .
6 p . p . p . p . p
7 . c . . . . . c .
8 . . . . . . . . .
9 r n b g k g b n r
0 1 2 3 4 5 6 7 8
0 R N B G . G B N R
1 . . . . K . . . .
2 . C . . . . . C .
3 P . P . P . P . P
4 . . . . . . . . .
5 . . . . . . . . .
6 p . p . p . p . p
7 . c . . . . . c .
8 . . . . . . . . .
9 r n b g k g b n r

interface

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store