1 前言
🚀获取源码,文末公众号回复【飞机】,即可。
⭐欢迎点赞留言
2 正文
2.1 展示
64MB GIF可以欣赏:https://www.z4a.net/images/2022/03/23/ae8bacca260b5e978f1dab8010d9a2a1.gif
2.2 项目结构
2.2 主要代码展示
package main; import data.Data; import utils.Load; import javax.sound.sampled.Clip; import javax.swing.*; public class Main { public static void main(String[] args) { // 创建窗口 JFrame frame = new JFrame("飞机大战"); // 添加 JPanel Data.canvas = new Canvas(frame); frame.setContentPane(Data.canvas); // 初始化 Data Data.init(); // 设置图标 frame.setIconImage(Load.image("ICON.png")); // 设置窗口可见 frame.setVisible(true); // 获取标题栏的高度和宽度 Data.TITLE_BOX_HEIGHT = frame.getInsets().top; // 设置大小 frame.setSize(Data.WIDTH, Data.HEIGHT + Data.TITLE_BOX_HEIGHT); // 窗口大小固定 frame.setResizable(false); // 窗口居中显示 frame.setLocationRelativeTo(frame.getOwner()); // 窗口关闭时结束程序 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 播放背景音乐 Load.sound("background").loop(Clip.LOOP_CONTINUOUSLY); } }
2.4 按钮相关类
package scenes; import data.Data; import scenes.connector.Scenes; import utils.Load; import utils.Rect; import java.awt.*; public class About implements Scenes { // 背景图片 Image background; // 确定按钮 Image[] buttonOk; // 按钮状态 int buttonOkStruts = 0; public About() { buttonOk = new Image[3]; background = Load.image("关于作者-背景.png"); buttonOk[0] = Load.image("确定.png"); buttonOk[1] = Load.image("确定-鼠标移上.png"); buttonOk[2] = Load.image("确定-鼠标按下.png"); } public void onKeyDown(int keyCode) { } public void onKeyUp(int keyCode) { } public void onMouse(int x, int y, int struts) { buttonOkStruts = 0; if(Rect.isInternal(x, y, 188, 600 + Data.TITLE_BOX_HEIGHT, 132, 42)) { buttonOkStruts = struts == Scenes.MOUSE_MOVED ? 1 : struts == Scenes.MOUSE_DOWN ? 2 : 0; if(struts == Scenes.MOUSE_UP) Data.canvas.switchScenes("Home"); } } public void draw(Graphics g) { // 绘制背景 Data.background.show(g); // 绘制关于作者 g.drawImage(background, 48, 60, null); // 绘制按钮 g.drawImage(buttonOk[buttonOkStruts], 188, 600, null); } }
2.5 背景音乐类
package utils; import javax.imageio.ImageIO; import javax.sound.sampled.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.ArrayList; public class Load { public static Image image(String path) { BufferedImage img = null; URL url = Load.class.getResource("/resources/img/" + path); try { img = ImageIO.read(url); } catch (IOException e) { e.printStackTrace(); } return img; } // 返回一段音乐 public static Clip sound(String path) { try { AudioInputStream ais = AudioSystem.getAudioInputStream(Load.class.getResourceAsStream("/resources/sound/" + path + ".wav")); Clip sound = AudioSystem.getClip(); sound.open(ais); return sound; } catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } return null; } public static void playSound(String path) { new Thread(() -> Load.sound(path).start()).start(); } }