本文为大家分享了java画出五子棋游戏棋盘的方法,供大家参考,具体内容如下
专业从事成都做网站、成都网站建设,高端网站制作设计,小程序设计,网站推广的成都做网站的公司。优秀技术团队竭力真诚服务,采用H5网站设计+CSS3前端渲染技术,响应式网站建设,让网站在手机、平板、PC、微信下都能呈现。建站过程建立专项小组,与您实时在线互动,随时提供解决方案,畅聊想法和感受。
棋盘模块:
画五子棋棋盘: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
Main.java不变
运行一下
遇到的问题:
1)Eclipse不识别文件夹下的图片
问题:文件夹中有图片,但是在Eclipse项目栏中不显示
解决办法:在Eclipse中,选中根目录,F5 refresh,就显示出来了。
更多有趣的经典小游戏实现专题,分享给大家:
C++经典小游戏汇总
python经典小游戏汇总
python俄罗斯方块游戏集合
JavaScript经典游戏 玩不停
java经典小游戏汇总
javascript经典小游戏汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。