GUI相关内容及案例贪吃蛇实现 【下】

简介: 简介 GUI的核心技术:Swing AWT 因为界面不美观 需要jre环境 学习的原因: 写出一些小工具 工作时维护到swing界面的概率极小 了解MVC架构,了解监听! AWT AWT介绍 包含了很多类和接口!GUI! 元素:窗口,按钮,文本框 java.awt 组件和容器 创建窗口组件 impo

AWT


窗口监听


import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
    public static void main(String[] args) {
        new WindowFrame();
    }
}
class WindowFrame extends Frame{
    public WindowFrame(){
        setBackground(Color.blue);
        setBounds(100,100,200,200);
        setVisible(true);
        this.addWindowListener(
                //匿名内部类
            new WindowAdapter() {
                @Override
                public void windowOpened(WindowEvent e) {
                    super.windowOpened(e);
                }
                //关闭窗口
                @Override
                public void windowClosing(WindowEvent e) {
                    System.out.println("windowClosing");
                    System.exit(0);
                }
                //激活窗口
                @Override
                public void windowActivated(WindowEvent e) {
                    WindowFrame source = (WindowFrame) e.getSource();
                    source.setTitle("被激活了");
                    System.out.println("windowActivated");
                }
            }
        );
    }
    /*class MyWindowListener extends WindowAdapter{
        @Override
        public void windowClosing(WindowEvent e) {
            setVisible(false);//隐藏窗口,通过按钮,隐藏当前窗口
            System.exit(0);//正常退出
        }
    }*/
}


键盘监听


import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
//键
public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame{
    public KeyFrame(){
        setBounds(1,2,300,400);
        setVisible(true);
        this.addKeyListener(new KeyAdapter() {
            //匿名内部类
            //键盘按下
            @Override
            public void keyPressed(KeyEvent e) {
                //获得键盘下的键是哪一个,当前的码
                int keyCode = e.getKeyCode();//不需要去记录这个数值,直接使用静态属性  VK_XXX
                System.out.println(keyCode);
                if (keyCode == KeyEvent.VK_UP){
                    System.out.println("你按下了上键");
                }
                //根据按下键的不同操作,产生不同结果
            }
        });
    }
}


Swing


窗口、面板


import javax.swing.*;
import java.awt.*;
public class JFrameDemo {
    //init();初始化
    public void init(){
        //顶级窗口
        JFrame frame = new JFrame("这是一个JFrame窗口");
        frame.setVisible(true);
        frame.setBounds(100,100,200,200);
        frame.setBackground(Color.blue);
        //设置文字Jlabel
        JLabel label = new JLabel("欢迎来到Java学习系列节目");
        frame.add(label);
        //让文本居中,设置水平对齐
        label.setHorizontalAlignment(SwingConstants.CENTER);
        //容器实例化
        Container container = frame.getContentPane();
        container.setBackground(Color.BLUE);
        //关闭事件
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        //建立一个窗口
        new JFrameDemo().init();
    }
}


弹窗


JDialog,用来被弹出,默认就有关闭事件!


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//主窗口
public class DialogDemo extends JFrame {
    public DialogDemo(){
        this.setVisible(true);
        this.setSize(700,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //JFrame 放东西,容器
        Container container = this.getContentPane();
        container.setLayout(null);
        //按钮
        JButton button = new JButton("点击弹出一个对话框");//创建
        button.setBounds(30,30,200,50);
        //点击这个按钮的时候,弹出一个弹窗
        button.addActionListener(new ActionListener() {//监听器
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹窗
                new MyDialogDemo();
            }
        });
        container.add(button);
    }
    public static void main(String[] args) {
        new DialogDemo();
    }
}
//弹窗的窗口
class MyDialogDemo extends JDialog{
    public MyDialogDemo(){
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        //this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container container = this.getContentPane();
        container.setLayout(null);
        container.add(new Label("秦老师带你学Java"));
    }
}


标签


label


new JLabel("xxx");


图标 ICON


import javax.swing.*;
import java.awt.*;
//图标,需要实现类,Frame需要继承
public class IconDemo extends JFrame implements Icon {
    private int width;
    private int height;
    public IconDemo(){}//无参构造
    public IconDemo(int width,int height){
        this.width = width;
        this.height = height;
    }
    public void init(){
        IconDemo iconDemo = new IconDemo(15, 15);
        //图标放在标签上,也可以放在按钮上!
        JLabel label = new JLabel("icontest",iconDemo,SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new IconDemo().init();
    }
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,height);
    }
    @Override
    public int getIconWidth() {
        return this.width;
    }
    @Override
    public int getIconHeight() {
        return this.height;
    }
}


图片 ImageIcon


import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame {
    public ImageIconDemo(){
        //获取图片的地址
        JLabel label = new JLabel("ImageIcon");
        URL url = ImageIconDemo.class.getResource("receive.jpg");
        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = this.getContentPane();
        container.add(label);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,400,400);
    }
    public static void main(String[] args) {
        new ImageIconDemo();
    }
}

面板


JPanel


import javax.swing.*;
import java.awt.*;
public class JPanelDemo extends JFrame {
    public JPanelDemo(){
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));//后面的参数的意思,间距
        JPanel panel1 = new JPanel(new GridLayout(1, 3));
        JPanel panel2 = new JPanel(new GridLayout(1, 2));
        JPanel panel3 = new JPanel(new GridLayout(2, 1));
        JPanel panel4 = new JPanel(new GridLayout(3, 2));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel2.add(new JButton("2"));
        panel2.add(new JButton("2"));
        panel3.add(new JButton("3"));
        panel3.add(new JButton("3"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        container.add(panel1);
        container.add(panel2);
        container.add(panel3);
        container.add(panel4);
        this.setVisible(true);
        this.setSize(500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JPanelDemo();
    }
}


JScrollPanel 滚动条


import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
    public JScrollDemo(){
        Container container = this.getContentPane();
        //文本域
        JTextArea jTextArea = new JTextArea(20, 50);
        jTextArea.setText("欢迎学习Java");
        JScrollPane scrollPane = new JScrollPane(jTextArea);
        container.add(scrollPane);
        this.setVisible(true);
        this.setBounds(100,100,300,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollDemo();
    }
}


按钮


图片按钮


import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButton01 extends JFrame {
    public JButton01(){
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL resource = JButton01.class.getResource("receive.jpg");
        Icon icon = new ImageIcon(resource);
        //把这个图标放在按钮上
        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("图片按钮");
        //add
        container.add(button);
        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButton01();
    }
}


单选按钮


import javax.swing.*;
import java.awt.*;
public class JButtonDemo02 extends JFrame {
    public JButtonDemo02(){
        Container container = this.getContentPane();
        //单选框
        JRadioButton radioButton1 = new JRadioButton("JRadioButton01");
        JRadioButton radioButton2 = new JRadioButton("JRadioButton02");
        JRadioButton radioButton3 = new JRadioButton("JRadioButton03");
        //由于单选框只能选择一个,分组,一个组中只能选择一个
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        group.add(radioButton3);
        container.add(radioButton1,BorderLayout.CENTER);
        container.add(radioButton2,BorderLayout.NORTH);
        container.add(radioButton3,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo02();
    }
}


多选按钮


import javax.swing.*;
import java.awt.*;
public class JButtonDemo03 extends JFrame {
    public JButtonDemo03(){
        Container container = this.getContentPane();
        //多选框
        JCheckBox checkBox01 = new JCheckBox("checkBox01");
        JCheckBox checkBox02 = new JCheckBox("checkBox02");
        container.add(checkBox01,BorderLayout.NORTH);
        container.add(checkBox02,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo03();
    }
}


下拉框


import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01(){
        Container container = this.getContentPane();
        JComboBox status = new JComboBox();
        status.addItem(null);
        status.addItem("正在上映");
        status.addItem("已下架");
        status.addItem("即将上映");
        container.add(status);
        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
    new TestComboboxDemo01();
    }
}


列表框


import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class TestComboboxDemo02 extends JFrame{
    public TestComboboxDemo02(){
        Container container = this.getContentPane();
        //生成列表的内容
        //String[] contents = {"1","2","3"};
        Vector contents = new Vector();
        //列表中需要放入内容
        JList jList = new JList(contents);
        contents.add("zhangsan");
        contents.add("lisi");
        contents.add("wangwu");
        container.add(jList);
        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestComboboxDemo02();
    }
}


  • 应用场景


  • 选择地区,或者一些单个选项


  • 列表,展示信息,一般是动态扩容!


文本框


  • 文本框


import javax.swing.*;
import java.awt.*;
public class TestTextDemo01 extends JFrame {
    public TestTextDemo01(){
        Container container = this.getContentPane();
        JTextField textField = new JTextField("hello");
        JTextField textField2 = new JTextField("world",20);
        container.add(textField,BorderLayout.NORTH);
        container.add(textField2,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestTextDemo01();
    }
}


  • 密码框


import javax.swing.*;
import java.awt.*;
public class TestTextDemo02 extends JFrame{
    public TestTextDemo02(){
        Container container = this.getContentPane();
        //尽量使用面板操作
        JPasswordField passwordField = new JPasswordField();//******
        passwordField.setEchoChar('*');
        container.add(passwordField);
        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestTextDemo02();
    }
}


  • 文本域


import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
    public JScrollDemo(){
        Container container = this.getContentPane();
        //文本域
        JTextArea jTextArea = new JTextArea(20, 50);
        jTextArea.setText("欢迎学习Java");
        JScrollPane scrollPane = new JScrollPane(jTextArea);
        container.add(scrollPane);
        this.setVisible(true);
        this.setBounds(100,100,300,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollDemo();
    }
}


贪吃蛇


  1. 定义数据


  1. 画上去


  1. 监听事件
  1. 键盘
  2. 事件


import javax.swing.*;
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setBounds(10,10,900,720);
        frame.setResizable(false);//窗口大小不可变
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new GamePanel());
        //正常的游戏内容都在Panel上
    }
}
====================================================================================
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
//游戏的面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
    //定义蛇的数据结构
    int length;//蛇的长度
    int[] snakeX = new int[600];//蛇的X坐标 25*25
    int[] snakeY = new int[500];//蛇的Y坐标 25*25
    String fx;
    //食物的坐标
    int foodx;
    int foody;
    Random random = new Random();
    int score;//成绩
    //游戏当前的状态:开始,停止
    boolean isStart = false;//默认是不开始!
    boolean isFail = false;//游戏失败状态
    //定时器   以ms为单位  1000ms=1s
    Timer timer = new Timer(100,this);//100毫秒执行一次
    //构造器
    public GamePanel(){
        init();
        //获得焦点和键盘事件
        this.setFocusable(true);//获得焦点事件
        this.addKeyListener(this);//获得键盘监听事件
        timer.start();//游戏一开始定时器就启动
    }
    //初始化方法
    public void init(){
        length = 3;
        snakeX[0] = 100;snakeY[0] = 100;//脑袋的坐标
        snakeX[1] = 75;snakeY[1] = 100;//第一个身体的坐标
        snakeX[2] = 50;snakeY[2] = 100;//第二个身体的坐标
        fx = "R";//初始方向向右
        //把食物随机分布在界面上!
        foodx = 25 + 25*random.nextInt(34);
        foody = 75 + 25*random.nextInt(24);
        score = 0;
    }
    //绘制面板,我们游戏中的所有东西,都是用这个画笔来画
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        //绘制静态的面板
        this.setBackground(Color.white);
        Data.header.paintIcon(this,g,25,11);//头部广告栏
        g.fillRect(25,75,850,600);//默认的游戏界面
        //画积分
        g.setColor(Color.WHITE);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度"+length,750,35);
        g.drawString("分数"+score,750,50);
        //画食物
        Data.food.paintIcon(this,g,foodx,foody);
        //把小蛇画上去
        if (fx.equals("R")){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右,需要通过方向来判断
        }else if (fx.equals("L")){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右,需要通过方向来判断
        }else if (fx.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右,需要通过方向来判断
        }else if (fx.equals("D")){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右,需要通过方向来判断
        }
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//第一个身体的坐标
        }
        //游戏状态
        if (isStart==false){
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体
            g.drawString("按下空格开始游戏",300,300);
        }
        if (isFail){
            g.setColor(Color.red);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("失败,按下空格重新开始",300,300);
        }
    }
    //键盘监听事件
    @Override
    public void keyTyped(KeyEvent e) {
    }
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//获得键盘按键是哪一个
        if (keyCode == KeyEvent.VK_SPACE){//如果按下的是空格键
            if (isFail){
                //重新开始
                isFail = false;
                init();
            }else {
                isStart = !isStart;//取反
            }
            repaint();
        }
        //小蛇移动
        if (keyCode==KeyEvent.VK_UP){
            fx = "U";
        }else if (keyCode==KeyEvent.VK_DOWN){
            fx = "D";
        }else if (keyCode==KeyEvent.VK_LEFT){
            fx = "L";
        }else if (keyCode==KeyEvent.VK_RIGHT){
            fx = "R";
        }
    }
    //事件监听---需要通过固定事件来刷新
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && isFail == false){//如果游戏是开始状态,就让小蛇动起来!
            //吃食物
            if (snakeX[0] == foodx && snakeY[0] == foody){
                length++;//长度 + 1
                //分数加10
                score = score + 10;
                //再次随机生成事物
                foodx = 25 + 25*random.nextInt(34);
                foody = 75 + 25*random.nextInt(24);
            }
            //移动
            for (int i = length-1; i > 0; i--) {//后一节移到前一节的位置 snakeX[1] snakeX[0];
                snakeX[i] = snakeX[i-1];//向前移动一节
                snakeY[i] = snakeY[i-1];
            }
            //走向
            if (fx.equals("R")){
                snakeX[0] = snakeX[0]+25;
                if (snakeX[0]>850){snakeX[0] = 25;}//边界判断
            }else if (fx.equals("L")){
                snakeX[0] = snakeX[0]-25;
                if (snakeX[0]<0){snakeX[0] = 825;}//边界判断
            }else if (fx.equals("U")){
                snakeY[0] = snakeY[0]-25;
                if (snakeY[0]<75){snakeY[0] = 650;}//边界判断
            }else if (fx.equals("D")) {
                snakeY[0] = snakeY[0] + 25;
                if (snakeY[0] > 650) {snakeY[0] = 75;}//边界判断
            }
            //失败判断,撞到自己就算失败
            for (int i = 1; i < length; i++){
                if (snakeX[0]==snakeX[i] && snakeY[0]==snakeY[i]){
                    isFail = true;
                }
            }
            repaint();//重画页面
        }
        timer.start();//定时器开启
    }
    @Override
    public void keyReleased(KeyEvent e) {
    }
}
===================================================================================
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
    //图片要放在src文件中
    //相对路径  tx.jpg
    //绝对路径  /   相当于当前项目
    public static URL headerURL = Data.class.getResource("/statics/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);
    public static URL upURL = Data.class.getResource("/statics/up.png");
    public static URL downURL = Data.class.getResource("/statics/down.png");
    public static URL leftURL = Data.class.getResource("/statics/left.png");
    public static URL rightURL = Data.class.getResource("/statics/right.png");
    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 URL bodyURL = Data.class.getResource("/statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
    public static URL foodURL = Data.class.getResource("/statics/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);
}
相关文章
62.【GUI 贪吃蛇】
62.【GUI 贪吃蛇】
36 0
如何用easyx播放音乐,插入图片
如何用easyx播放音乐,插入图片
254 0
|
6月前
|
数据可视化 Python
六种酷炫Python运行进度条
六种酷炫Python运行进度条
|
3月前
|
C# UED 开发者
WPF打印功能实现秘籍:从页面到纸张,带你玩转WPF打印技术大揭秘!
【8月更文挑战第31天】在WPF应用开发中,打印功能至关重要,不仅能提升用户体验,还增强了应用的实用性。本文介绍WPF打印的基础概念与实现方法,涵盖页面元素打印、打印机设置及打印预览。通过具体案例,展示了如何利用`PrintDialog`和`PrintDocument`控件添加打印支持,并使用`PrinterSettings`类进行配置,最后通过`PrintPreviewWindow`实现打印预览功能。
316 0
|
3月前
|
XML Linux C++
【Qt】图形化和纯代码实现Hello world的比较
【Qt】图形化和纯代码实现Hello world的比较
|
6月前
|
编解码 C++
Qt第一课 第一个ui界面
Qt第一课 第一个ui界面
87 2
|
6月前
|
程序员 C# Python
100行python代码,轻松完成贪吃蛇小游戏_c#游戏100行代码(2)
100行python代码,轻松完成贪吃蛇小游戏_c#游戏100行代码(2)
|
6月前
|
存储 程序员 C#
100行python代码,轻松完成贪吃蛇小游戏_c#游戏100行代码
100行python代码,轻松完成贪吃蛇小游戏_c#游戏100行代码
|
C++ Python
Python+Qt抽奖点名工具源码窗体程序
Python+Qt抽奖点名工具源码窗体程序
145 0
Python+Qt抽奖点名工具源码窗体程序
|
数据可视化 开发工具 C语言
python超级画板白板程序源码
python超级画板白板程序源码
200 0