Java实现两人五子棋游戏(二) 画出棋盘
程序员文章站
2022-06-19 23:44:54
本文为大家分享了java画出五子棋游戏棋盘的方法,供大家参考,具体内容如下
棋盘模块:
画五子棋棋盘:19条横线、19条竖线
步骤一:显示棋盘
我有一张名为ches...
本文为大家分享了java画出五子棋游戏棋盘的方法,供大家参考,具体内容如下
棋盘模块:
画五子棋棋盘:19条横线、19条竖线
步骤一:显示棋盘
我有一张名为chessboard.png的棋盘,位置为根目录/res/drawable/chessboard/png,现在我要显示这张图片。
drawchessboard.java
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
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
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,就显示出来了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 巴适得板,来看看重庆机场美食攻略吧