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方法,顯示當前繪制的靜態窗口如下: