这样的棋盘中,如何实现棋盘的格子随鼠标移动而高亮public ChessGameFrame(int width, int height) { setTitle("斗兽棋"); //设置标题 this.WIDTH = width; this.HEIGTH = height; this.ONE_CHESS_SIZE = (HEIGTH * 4 / 5) / 9; setSize(WIDTH, HEIGTH); setLocationRelativeTo(null); // Center the window. setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //设置程序关闭按键,如果点击右上方的叉就游戏全部关闭了 setLayout(null); addRestart(); addGiveUp(); addUndo(); addChessboard(); addLabel(); addLoadButton(); addSave(); addAImode(); addAImodeGreedy(); addBackground(); }public CellComponent(Color background, Point location, int size) { setLayout(new GridLayout(1,1)); setLocation(location); setSize(size, size); this.background = background; } @Override protected void paintComponent(Graphics g) { super.paintComponents(g); g.setColor(background); g.fillRect(1, 1, this.getWidth()-1, this.getHeight()-1); } }且不能与鼠标点击相冲突
时间: 2024-01-09 10:05:27 浏览: 26
可以通过添加鼠标移动监听器来实现棋盘格子的高亮。在棋盘上添加一个MouseMotionListener,然后在mouseMoved()方法中计算鼠标所在的格子位置,然后将该格子的颜色设置为高亮色即可。
示例代码:
```
//在ChessGameFrame中添加以下代码
private CellComponent highlightedCell; //记录当前高亮的格子
private void addChessboard() {
chessboard = new ChessboardComponent();
chessboard.setLocation(0, 0);
chessboard.setSize(WIDTH, HEIGTH);
chessboard.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//鼠标点击事件处理
//...
}
});
chessboard.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
//鼠标移动事件处理
Point p = e.getPoint();
int row = (int) Math.round((p.getY() - ChessboardComponent.MARGIN) / ONE_CHESS_SIZE);
int col = (int) Math.round((p.getX() - ChessboardComponent.MARGIN) / ONE_CHESS_SIZE);
if (row >= 0 && row < Chessboard.ROWS && col >= 0 && col < Chessboard.COLS) {
//计算鼠标所在的格子位置,如果位置不同于当前高亮的格子,则设置新的高亮格子
CellComponent cell = chessboard.getCell(row, col);
if (cell != highlightedCell) {
if (highlightedCell != null) {
highlightedCell.setBackground(highlightedCell.getBackground().darker()); //取消当前高亮格子
}
highlightedCell = cell;
highlightedCell.setBackground(highlightedCell.getBackground().brighter()); //设置新的高亮格子
}
} else {
//鼠标移出棋盘,取消当前高亮格子
if (highlightedCell != null) {
highlightedCell.setBackground(highlightedCell.getBackground().darker());
highlightedCell = null;
}
}
}
});
add(chessboard);
}
//在CellComponent中添加以下代码
@Override
protected void processMouseEvent(MouseEvent e) {
//处理鼠标事件,不做任何处理,避免与父组件ChessboardComponent的鼠标事件相冲突
}
```