这样的棋盘中,如何实现棋盘的格子随鼠标移动而高亮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-07 08:05:46 浏览: 93
您可以在CellComponent中添加鼠标监听器(MouseListener)和鼠标移动监听器(MouseMotionListener),在鼠标进入(mouseEntered)和鼠标移动(mouseMoved)事件触发时设置高亮背景颜色,鼠标离开(mouseExited)时还原颜色。具体实现可以参考以下代码:
```
public class CellComponent extends JPanel {
private Color background;
private Color highlightColor;
private Point location;
private int size;
public CellComponent(Color background, Point location, int size) {
setLayout(new GridLayout(1,1));
setLocation(location);
setSize(size, size);
this.background = background;
this.highlightColor = new Color(255, 255, 153); // 设置高亮颜色
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
setBackground(highlightColor);
}
@Override
public void mouseExited(MouseEvent e) {
setBackground(background);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
setBackground(highlightColor);
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(background);
g.fillRect(1, 1, this.getWidth()-1, this.getHeight()-1);
}
}
```
阅读全文