GUI简单实战——贪吃蛇

时间:2020-07-15 01:25:45   收藏:0   阅读:53

将前面学到的GUI基础知识完成实战,完成一个简单的贪吃蛇项目

项目功能

效果截图

技术分享图片

逻辑分析

代码分析

已经在代码上传到github上面注释很详细

踩坑

JFrame的窗口大小

窗口宽度= 输入宽度+窗口左边框+窗口右边框

窗口高度= 输入高度+窗口上边框+窗口下边框

jframe.setSize(Datas.GameWidth+3+3,Datas.GameHeight+32+3);

需要加上窗口左边框+窗口右边框和窗口上边框+窗口下边框,但是每一个项目的边框大小都是不一样的。所以需要先去测试边框大小

package com.greedy_snake;
import java.awt.*;
public class Main {
    public static void main(String[] args) {
        //创建一个窗口
        GameFrame gameFrame = new GameFrame();
        Dimension di = gameFrame.getContentPane().getSize();
        System.out.println("内容面板宽度"+di.width);//宽
        System.out.println("内容面板的高度"+di.height);//高
    }
}
package com.greedy_snake;

import javax.swing.*;
import java.awt.*;

public class GameFrame extends JFrame {
    public GameFrame(){
        //1 设置标题
        this.setTitle("贪吃蛇");
        //2 设置宽高 6 35是通过insets得到的
        this.setSize(Datas.GameWidth+3+3,Datas.GameHeight+32+3);
        //3 设置窗口居中
        this.setLocationRelativeTo(null);
        //4 设置点击窗口的×关闭
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //5 设置游戏窗口大小不可拉伸
        this.setResizable(false);
        //6 设置可见
        this.setVisible(true);
        /*7 得到窗口的边界区域
        需要放在setVisible下面输出的4个结果才不是0*/
        Insets insets = getInsets();
        System.out.println("窗口边框上"+insets.top);//上
        System.out.println("窗口边框下"+insets.bottom);//下
        System.out.println("窗口边框左"+insets.left);//左
        System.out.println("窗口边框右"+insets.right);//右
    }
}

技术分享图片

得到窗口的边界区域,需要放在setVisible下面输出的4个结果才不是0,不能在setSize中直接Datas.GameWidth+insets.left+insets.right

ImageDemo.class.getResource路径问题

两个例子给你就很理解了

技术分享图片

技术分享图片

原文:https://www.cnblogs.com/10134dz/p/13302950.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!