本文为大家分享了java画出五子棋游戏棋盘的方法,供大家参考,具体内容如下
棋盘模块:
画五子棋棋盘:19条横线、19条竖线
步骤一:显示棋盘
我有一张名为chessboard.png的棋盘,位置为根目录/res/drawable/chessboard/png,现在我要显示这张图片。
drawchessboard.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package xchen.test.simplegobang; import java.awt.graphics; import java.awt.image; import java.awt.toolkit; import javax.swing.jpanel; public class drawchessboard extends jpanel{ public image boardimg; public drawchessboard() { boardimg = toolkit.getdefaulttoolkit().getimage( "res/drawable/chessboard.png" ); if (boardimg == null ) system.err.println( "png do not exist" ); } @override protected void paintcomponent(graphics g) { // todo auto-generated method stub super .paintcomponent(g); int imgwidth = boardimg.getwidth( this ); int imgheight = boardimg.getheight( this ); int fwidth = getwidth(); int fheight= getheight(); int x=(fwidth-imgwidth)/ 2 ; int y=(fheight-imgheight)/ 2 ; g.drawimage(boardimg, x, y, null ); } } |
main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package xchen.test.simplegobang; import java.awt.container; import javax.swing.jframe; import xchen.test.simplegobang.drawchessboard; public class main extends jframe{ private drawchessboard drawchessboard; public main() { drawchessboard = new drawchessboard(); //frame标题 settitle( "单机五子棋" ); container containerpane =getcontentpane(); containerpane.add(drawchessboard); } public static void main(string[] args) { main m = new main(); m.setvisible( true ); } } |
运行一下
步骤二:为棋盘画上横竖线
drawchessboard.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package xchen.test.simplegobang; import java.awt.graphics; import java.awt.image; import java.awt.toolkit; import javax.swing.jpanel; public class drawchessboard extends jpanel{ public image boardimg; final private int rows = 19 ; public drawchessboard() { boardimg = toolkit.getdefaulttoolkit().getimage( "res/drawable/chessboard2.png" ); if (boardimg == null ) system.err.println( "png do not exist" ); } @override protected void paintcomponent(graphics g) { // todo auto-generated method stub super .paintcomponent(g); int imgwidth = boardimg.getwidth( this ); int imgheight = boardimg.getheight( this ); int fwidth = getwidth(); int fheight= getheight(); int x=(fwidth-imgwidth)/ 2 ; int y=(fheight-imgheight)/ 2 ; g.drawimage(boardimg, x, y, null ); int margin = x; int span_x=imgwidth/rows; int span_y=imgheight/rows; //画横线 for ( int i= 0 ;i<rows;i++) { g.drawline(x, y+i*span_y, fwidth-x,y+i*span_y); } //画竖线 for ( int i= 0 ;i<rows;i++) { g.drawline(x+i*span_x, y, x+i*span_x,fheight-y); } } } |
main.java不变
运行一下
遇到的问题:
1)eclipse不识别文件夹下的图片
问题:文件夹中有图片,但是在eclipse项目栏中不显示
解决办法:在eclipse中,选中根目录,f5 refresh,就显示出来了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/v_xchen_v/article/details/53420203