这一直让我感到困惑,我有一块板,我希望能够将棋子从一个地方移动到另一个地方。我已经将框架设置为网格布局,每个网格单元都有一个新的 JPanel 实现mouseListener ..如何注册点开始和结束,以便我可以移动棋盘格?我无法将我所在的点保存到一个临时点,因为每当我单击另一个点时它都会改变..
这是代码:
public class Tiles extends JPanel implements MouseListener {
Color c2, cc, tmp;
boolean isWhite, hasChecker, isHighlighted;
int i, j;
ArrayList<Point> al = new ArrayList<Point>();
ArrayList<Point> TempArray = new ArrayList<Point>();
Point start;
Point temp;
public Tiles(Color c, Point s){
this.setSize(75, 75);
this.setLayout(null);
this.addMouseListener(this);
this.c2 = c;
tmp = c2;
this.start = s;
}
public void setWhite(boolean isWhite){
this.isWhite = isWhite;
}
public void hasChecker(boolean hasChecker){
this.hasChecker = hasChecker;
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
super.paintComponent(g2);
//if(isClicked == true)
// highlightPossibleMoves(start);
drawTile(g2);
if(hasChecker == true)
addCheckers(g2);
}
public void drawTile(Graphics2D g2){
g2.setColor(c2);
g2.fillRect(3, 3, 75, 75);
}
public void addCheckers(Graphics2D g2){
if(isWhite == true){
g2.setColor(Color.white);
}
else{
g2.setColor(Color.black);
}
Ellipse2D.Double circle = new Ellipse2D.Double(13, 11, 50, 50);
g2.fill(circle);
}
public boolean highlightPossibleMoves(Point start){
al = LOA.b.getPossibleMoves(start);
if(!al.isEmpty()){
for(int i = 0; i<al.size(); i++){
LOA.Jboard[al.get(i).getY()][al.get(i).getX()].c2 = Color.green;
LOA.Jboard[al.get(i).getY()][al.get(i).getX()].repaint();
}
return true;
}
return false;
}
public Point getThisPoint(){
return this.start;
}
public boolean isPossible(Point p){
if (TempArray.contains(p)){
System.out.println("contains");
return true;
}
return false;
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
if(isHighlighted = true){
LOA.initBoard();
}
if(highlightPossibleMoves(getThisPoint()) == true){
this.isHighlighted = true;
}
if(isPossible(getThisPoint()))
LOA.move(this.temp, getThisPoint());
else{
System.out.println("x =" + this.start.getX() + "y =" + this.start.getY());
this.temp = new Point(getThisPoint().getX(), getThisPoint().getY());
}
this.repaint();
this.validate();
}
}