本文為大家分享了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