我正在尝试使用Java制作Tic Tac Toe游戏而不必担心游戏中的人工智能。我只是想绘制它并做一些我要解释的事情。 这是我要绘制的tic tac toe的代码:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class JFrameTicTacToeInternet extends JFrame implements MouseListener{
public JFrameTicTacToeInternet(String title){
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,500);
addMouseListener(this);
}
public void paint(Graphics g){
int totalWidth = 200;
int verticalCenter = (this.getHeight() - totalWidth)/2;
int horizontalCenter = (this.getWidth() - totalWidth)/2;
g.setColor(Color.white);
g.fillRect(0,0,this.getWidth(), this.getHeight());
g.setColor(Color.black);
// draw big grid
this.drawGrid(g, horizontalCenter, verticalCenter, totalWidth);
}
private void drawGrid(Graphics g, int x, int y, int width) {
// draw box around grid
g.drawRect(x, y, width, width);
// draw vertical grid lines
g.drawLine(width / 3 + x, y, width / 3 + x, y + width);
g.drawLine(width / 3 * 2 + x, y, width / 3 * 2 + x, y + width);
// draw horizontal grid lines
g.drawLine(x, width / 3 + y, x + width, width / 3 + y);
g.drawLine(x, width / 3 * 2 + y, x + width, width / 3 * 2 + y);
}
结果是tic tac toe。 现在我想补充一点,当你用鼠标进入正方形时,它会变成蓝色。 例如:我用鼠标输入右下角的方块,它的颜色为蓝色。当我退出那个方格时,颜色必须返回白色。
我想用mouseEntered和mouseExited来做,但我真的不知道怎么做。
提前谢谢。