GUI编程
04 贪吃蛇小游戏
4.1 第一步:先绘制一个静态的面板
首先,需要新建两个类,一个StartGame类作为游戏的主启动类;一个GamePanel类作为游戏的面板类。此外,再新建一个Data类作为数据中心(存放了小蛇各部分图像的URL及ImageIcon)。代码如下:
StartGame:
package com.duo.snake;import javax.swing.*;//游戏的主启动类
public class StartGame {public static void main(String[] args) {JFrame frame = new JFrame();frame.setVisible(true);frame.setResizable(false);frame.setTitle("贪吃蛇-2023");frame.setBounds(5, 10, 915, 740);frame.setLocationRelativeTo(null);frame.add(new GamePanel());frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}
}
GamePanel:
package com.duo.snake;import javax.swing.*;
import java.awt.*;//游戏的面板
public class GamePanel extends JPanel {@Overrideprotected void paintComponent(Graphics g) {super.paintComponent(g); //起到清屏的作用//先绘制一个静态的面板Data.header.paintIcon(this, g, 25, 11);g.fillRect(25, 75, 850, 600);this.setBackground(Color.white);}
}
Data:
package com.duo.snake;import javax.swing.*;
import java.net.URL;//数据中心
public class Data {//相对路径 tx.jpg//绝对路径 /:相当于当前的项目public static URL headerURL = Data.class.getResource("static/header.png");public static URL upURL = Data.class.getResource("static/up.png");public static URL downURL = Data.class.getResource("static/down.png");public static URL leftURL = Data.class.getResource("static/left.png");public static URL rightURL = Data.class.getResource("static/right.png");public static URL bodyURL = Data.class.getResource("static/body.png");public static URL foodURL = Data.class.getResource("static/food.png");public static ImageIcon header = new ImageIcon(headerURL);public static ImageIcon up = new ImageIcon(upURL);public static ImageIcon down = new ImageIcon(downURL);public static ImageIcon left = new ImageIcon(leftURL);public static ImageIcon right = new ImageIcon(rightURL);public static ImageIcon body = new ImageIcon(bodyURL);public static ImageIcon food = new ImageIcon(foodURL);}
最后,通过StartGame中main方法,显示当前绘制的静态窗口如下: