怎么让java运行时棋盘随鼠标移动而高亮public class ChessboardComponent extends JComponent { private final CellComponent[][] gridComponents = new CellComponent[CHESSBOARD_ROW_SIZE.getNum()][CHESSBOARD_COL_SIZE.getNum()]; private final int CHESS_SIZE; private final Set<ChessboardPoint> riverCell = new HashSet<>(); private GameController gameController; public ChessboardComponent(int chessSize) { CHESS_SIZE = chessSize; int width = CHESS_SIZE * 7; int height = CHESS_SIZE * 9; enableEvents(AWTEvent.MOUSE_EVENT_MASK);// Allow mouse events to occur setLayout(null); // Use absolute layout. setSize(width, height); System.out.printf("chessboard width, height = [%d : %d], chess size = %d\n", width, height, CHESS_SIZE); initiateGridComponents(); }
时间: 2024-01-18 12:03:02 浏览: 26
你可以在ChessboardComponent类中添加MouseMotionListener,重写mouseMoved()方法,然后在该方法中计算当前鼠标所在的棋盘格子,并将该格子高亮显示。
具体实现步骤如下:
1. 在ChessboardComponent类中添加MouseMotionListener。
2. 重写mouseMoved()方法,在该方法中获取当前鼠标的坐标。
3. 根据鼠标坐标计算出当前所在的棋盘格子。
4. 将该格子高亮显示。
下面是一个示例代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChessboardComponent extends JComponent {
private final CellComponent[][] gridComponents = new CellComponent[CHESSBOARD_ROW_SIZE.getNum()][CHESSBOARD_COL_SIZE.getNum()];
private final int CHESS_SIZE;
private final Set<ChessboardPoint> riverCell = new HashSet<>();
private GameController gameController;
private ChessboardPoint highlightedCell = null;
public ChessboardComponent(int chessSize) {
CHESS_SIZE = chessSize;
int width = CHESS_SIZE * 7;
int height = CHESS_SIZE * 9;
enableEvents(AWTEvent.MOUSE_EVENT_MASK);// Allow mouse events to occur
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int row = y / CHESS_SIZE;
int col = x / CHESS_SIZE;
if (row >= 0 && row < CHESSBOARD_ROW_SIZE.getNum() && col >= 0 && col < CHESSBOARD_COL_SIZE.getNum()) {
if (highlightedCell != null) {
gridComponents[highlightedCell.getRow()][highlightedCell.getCol()].setHighlighted(false);
}
gridComponents[row][col].setHighlighted(true);
highlightedCell = new ChessboardPoint(row, col);
}
}
});
setLayout(null); // Use absolute layout.
setSize(width, height);
System.out.printf("chessboard width, height = [%d : %d], chess size = %d\n", width, height, CHESS_SIZE);
initiateGridComponents();
}
}
```
在这个示例中,我们在ChessboardComponent类中添加了MouseMotionListener,并重写了mouseMoved()方法。在该方法中,我们计算出当前鼠标所在的棋盘格子,并将该格子高亮显示。注意,我们使用highlightedCell来记录当前高亮的格子,以便在鼠标移动时取消之前高亮的格子。