Java 五子棋(一绘)制棋盘、棋子
作者:互联网
五子棋
界面
- 需要继承JFrame,重写JFrame中的paint方法(JFrame中的paint方法每一次拖动,放大或缩小都会重新刷新绘制)
- 在paint方法中绘制棋盘(网格)
网格
- 行、列数、各自间隔
棋子
- 白棋和黑棋
Code
- 需要创建一个窗体继承JFrame方法,设置窗体的大小、标题、退出进程、可视化
public void showUI(){
JFrame jf=this;
jf.setTitle("五子棋");
jf.setSize(800,800);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
- 改写JFrame中的paint方法,可在这里面绘制网格线,每一次拖动界面都会被重新刷新,不会因为拖动界面而消失
public void paint(Graphics graphics){
super.paint(graphics);
for(int i=0;i<11;i++) {
graphics.drawLine(StudentIface.x, StudentIface.y+i*StudentIface.SIZE,StudentIface.x+StudentIface.SIZE*StudentIface.L, StudentIface.y+i*StudentIface.SIZE);
graphics.drawLine(StudentIface.x+i*StudentIface.SIZE, StudentIface.y+StudentIface.SIZE*StudentIface.R,StudentIface.x+i*StudentIface.SIZE,StudentIface.y);
}
System.out.println("画笔");
}
- 创建一个接口interface,写下其棋子的属性(也可直接写在监听器,当属性较多时,可能就没那么美观了)
public interface StudentIface {
public int x=100;
public int y=100;
public int L=10;
public int R=10;
public int SIZE=40;
}
- 创建一个监听器继承鼠标监听器,设置画笔的方法,使得监听器调用的画笔对象赋值给申明的对象
public class StudentLisenter implements MouseListener {
Graphics graphics;
public void setGraphics(Graphics graphics){
this.graphics=graphics;
System.out.println(graphics+"g");
}
- 在按下这个方法中,设置一个判断条件,判断是奇数还是偶数,若为奇数时,绘制黑棋,若为偶数是,绘制白棋(可以用%取余来判定,除以2时,结果不是0就是1)
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
count++;
for (int i = 0; i < SIZE; i++) {
if (count % 2 == 1) {
graphics.setColor(Color.BLACK);
graphics.fillOval(x, y, 20, 20);
} else {
graphics.setColor(Color.WHITE);
graphics.fillOval(x, y, 20, 20);
}
}
}
- 申明一个画笔对象g赋值给窗体对象得到的画笔方法,创建监听器对象,将其加到窗体对象中,监听器对象调用设置的画笔对象
Graphics g=jf.getGraphics();
StudentLisenter studentLisenter=new StudentLisenter();
jf.addMouseListener(studentLisenter);
studentLisenter.setGraphics(g);
标签:JFrame,Java,int,五子棋,监听器,graphics,jf,一绘,public 来源: https://blog.csdn.net/yxiulian/article/details/121328485