GUI编程笔记-实战简单的小游戏贪吃蛇

概述

本笔记是根据b站up主,遇见狂神说,【狂神讲Java】学习,十分推荐!看完看会就是大神!

视频链接https://www.bilibili.com/video/BV1DJ411B75F?p=1

狂神:只要学不死,就往死里学!

1、简介

Gui核心技术:Swing、AWT,因为界面不美观、需要jre环境!

为什么要学习?

  • 可以写一些自己想要的小工具
  • 工作的时候可能需要维护swing界面,概率极小
  • 了解MVC,了解监听!

2、AWT

2.1、AWT介绍

  • 包含很多的类和接口!GUI:图形用户界面编程
  • 元素:窗口、按钮、文本框
  • java.awt包内

在这里插入图片描述

2.2、组件和容器

1、frame
package com.xwy.lesson01;
import java.awt.*;
/**
 * @author levi
 * @create 2020/7/27 6:42 下午
 */
public class TestFrame {
    public static void main(String[] args){
        Frame frame = new Frame("我的第一个java图形界面窗口");
        //设置可见性
        frame.setVisible(true);
        //窗口大小
        frame.setSize(400,400);
        //背景颜色
        frame.setBackground(new Color(85,150,68));
        //弹出的初始位置
        frame.setLocation(200,200);
        //设置大小固定
        frame.setResizable(false);
    }
}

封装

package com.xwy.lesson01;

import java.awt.*;

/**
 * @author levi
 * @create 2020/7/27 6:54 下午
 */
public class TestFream02 {
    public static void main(String[] args) {
        MyFrame myFrame1 = new MyFrame(100,100,200,200,Color.blue);
        MyFrame myFrame2 = new MyFrame(300,100,200,200,Color.red);
        MyFrame myFrame3 = new MyFrame(100,300,200,200,Color.pink);
        MyFrame myFrame4 = new MyFrame(300,300,200,200,Color.black);
    }
}
class MyFrame extends Frame{
    static  int id = 0;  //可能存在多个创路,所以需要一个计数器
    public  MyFrame(int x, int y, int w, int h,Color color){

        super("Myframe"+(++id));
        setBackground(color);
        setBounds(x,y,w,h);
        setVisible(true);
    }
}

发现还不能关闭啊!继续!

2、面板Panel

解决了关闭问题!监听事件!

package com.xwy.lesson01;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author levi
 * @create 2020/7/27 7:04 下午
 */
public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Panel panel = new Panel();
        //设置布局
        frame.setLayout(null);
        //坐标
        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(40,161,35));

        //panel设置坐标,相对于frame
        panel.setBounds(50,50,400,400);
        //设置颜色
        panel.setBackground(new Color(193,15,60));
        //面板放入
        frame.add(panel);
        frame.setVisible(true);

        //监听事件,监听窗口关闭事件
        //适配器模式
        frame.addWindowListener(new WindowAdapter() {
            //窗口点击关闭是要做的
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }
}

2.3、布局管理器

  • 流式布局
package com.xwy.lesson01;

import java.awt.*;

/**
 * @author levi
 * @create 2020/7/27 7:15 下午
 */

public class TestFlowLayout {
    public static void main(String[] args) {
        Frame frame = new Frame();
        //按钮
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        //设置为流式布局
        frame.setLayout(new FlowLayout(FlowLayout.CENTER)); //中间
        frame.setSize(200,200);
        //把按钮添加上去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.setVisible(true);
    }
}
  • 东西南北中
package com.xwy.lesson01;

import java.awt.*;

/**
 * @author levi
 * @create 2020/7/27 7:22 下午
 */
public class TestBorderLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestBorderLayout");

        Button button1 = new Button("East");
        Button button2 = new Button("West");
        Button button3 = new Button("South");
        Button button4 = new Button("North");
        Button button5 = new Button("Center");
        frame.add(button1,BorderLayout.EAST);
        frame.add(button2,BorderLayout.WEST);
        frame.add(button3,BorderLayout.SOUTH);
        frame.add(button4,BorderLayout.NORTH);
        frame.add(button5,BorderLayout.CENTER);
        frame.setSize(300,300);
        frame.setVisible(true);
    }
}
  • 表格布局
package com.xwy.lesson01;

import java.awt.*;

/**
 * @author levi
 * @create 2020/7/27 7:26 下午
 */
public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestGridLayout");
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");
        Button button6 = new Button("button6");

        frame.setLayout(new GridLayout(3,2));
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);
        frame.pack();//java函数,自动优化
        frame.setVisible(true);
    }
}
1、Demo练习

在这里插入图片描述

package com.xwy.lesson01;

import java.awt.*;

/**
 * @author levi
 * @create 2020/7/27 7:35 下午
 */
public class ExDemo {

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setSize(400,300);
        frame.setLocation(300,400);
        frame.setBackground(Color.blue);
        frame.setVisible(true);
        frame.setLayout(new GridLayout(2,1));
        //四个面板
        Panel panel1 = new Panel(new BorderLayout());
        Panel panel2= new Panel(new GridLayout(2,1));
        Panel panel3 = new Panel(new BorderLayout());
        Panel panel4 = new Panel(new GridLayout(2,1));

        panel1.add(new Button("Button-East"),BorderLayout.EAST);
        panel1.add(new Button("Button-West"),BorderLayout.WEST);
        panel2.add(new Button("Buttonp-2-1"));
        panel2.add(new Button("Buttonp-2-2"));
        panel1.add(panel2,BorderLayout.CENTER);

        panel3.add(new Button("Button-East2"),BorderLayout.EAST);
        panel3.add(new Button("Button-West2"),BorderLayout.WEST);
        for (int i = 0 ;i < 4; i++){
            panel4.add(new Button("for-"+i));
        }
        panel3.add(panel4,BorderLayout.CENTER);
        frame.add(panel1);
        frame.add(panel3);
    }
}
2、小结

在这里插入图片描述

2.4、事件监听

当某个事情发生的时候做什么?

package com.xwy.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author levi
 * @create 2020/7/27 7:56 下午
 */
public class TestActionEvent {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Button button = new Button();
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);
        frame.add(button,BorderLayout.CENTER);;
        frame.pack();
        windowsClose(frame);
        frame.setVisible(true);
    }
    private static  void windowsClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
class MyActionListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("aaaaa");
    }
}

多个按钮共享一个监听事件

package com.xwy.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author levi
 * @create 2020/7/27 8:14 下午
 */
public class TestActionTwo {
    public static void main(String[] args) {
        Frame frame = new Frame("开始-停止");
        Button button = new Button("start");
        Button button2 = new Button("stop");

        //可以显示的定义出发回返回的命令,如果不定义显示,则会走默认的值'
        //button2.setActionCommand("button-stop");

        MyMonitor myMonitor = new MyMonitor();
        button.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);

        frame.add(button,BorderLayout.NORTH);
        frame.add(button2,BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }
}
class MyMonitor implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮被电击了:mesg:"+e.getActionCommand());
        if (e.getActionCommand().equals("start")){

        }
    }
}

2.5、输入框TextField

package com.xwy.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author levi
 * @create 2020/7/27 8:24 下午
 */
public class TestText01 {
    public static void main(String[] args) {
        new MyFrame();
    }
}
class MyFrame extends Frame{
    public  MyFrame(){
        TextField textField = new TextField();
        add(textField);
        //监听文本框的文字
        MyActionListener2 myActionListener2 = new MyActionListener2();
        //按下enter,出发事件
        textField.addActionListener(myActionListener2);
        //设置替换编码
        textField.setEchoChar('*');//输入隐藏,但是后台正常获取,比如输入密码
        setVisible(true);
        pack();
    }
}
class MyActionListener2 implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField textField = (TextField) e.getSource();//获得一些资源,返回一个对象
        System.out.println(textField.getText());
        textField.setText(""); //回车后文字消失
    }
}

2.6、简易计算器

oop原则:组合,大于继承

class a extends b{
  
}
class a{
  private B b;
}

package com.xwy.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author levi
 * @create 2020/7/27 8:41 下午
 */
public class TestCalc {
    public static void main(String[] args) {
        new Calclator();
    }
}
//计算机类
class Calclator extends Frame{
    public Calclator(){
        TextField num1 = new TextField(10);//最大能填字符数
        TextField num2 = new TextField(10);//字符数
        TextField num3 = new TextField(20);//字符数
        Button button = new Button("=");
        button.addActionListener(new MyCalclatorListener(num1,num2,num3));
        Label label = new Label("+");
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }
}
//监听器类
class MyCalclatorListener implements ActionListener{
    //获取三个变量
    private  TextField num1,num2,num3;
    public MyCalclatorListener(TextField num1,TextField num2,TextField num3){
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获得数值
        int n1 = Integer.parseInt(num1.getText());
        int n2 = Integer.parseInt(num2.getText());
        //运算后放到第三个框
        num3.setText(""+(n1+n2));
        //清除前俩框
        num1.setText("");
        num2.setText("");
    }
}

优化

组合,完全改为面向对象的写法

package com.xwy.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author levi
 * @create 2020/7/27 8:41 下午
 */
public class TestCalc {
    public static void main(String[] args) {
        new Calclator().loadFrame();
    }
}
//计算机类
class Calclator extends Frame{
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
            num1 = new TextField(10);//最大能填字符数
            num2 = new TextField(10);//字符数
            num3 = new TextField(20);//字符数
            Button button = new Button("=");
            button.addActionListener(new MyCalclatorListener(this));
            Label label = new Label("+");
            setLayout(new FlowLayout());
            add(num1);
            add(label);
            add(num2);
            add(button);
            add(num3);
            pack();
            setVisible(true);
    }
}
//监听器类
class MyCalclatorListener implements ActionListener{
    Calclator calclator = null;
    public MyCalclatorListener(Calclator calclator){
        this.calclator = calclator;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        int n1 = Integer.parseInt(calclator.num1.getText());
        int n2 = Integer.parseInt(calclator.num2.getText());
        calclator.num3.setText(""+(n1+n2));
        calclator.num1.setText("");
        calclator.num2.setText("");
    }
}

内部类

  • 更好的包装
package com.xwy.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author levi
 * @create 2020/7/27 8:41 下午
 */
public class TestCalc {
    public static void main(String[] args) {
        new Calclator().loadFrame();
    }
}
//计算机类
class Calclator extends Frame{
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
            num1 = new TextField(10);//最大能填字符数
            num2 = new TextField(10);//字符数
            num3 = new TextField(20);//字符数
            Button button = new Button("=");
            button.addActionListener(new MyCalclatorListener());
            Label label = new Label("+");
            setLayout(new FlowLayout());
            add(num1);
            add(label);
            add(num2);
            add(button);
            add(num3);
            pack();
            setVisible(true);
    }
    //监听器类
    private class MyCalclatorListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());
            num3.setText(""+(n1+n2));
            num1.setText("");
            num2.setText("");
        }
    }
}

2.7、画笔

package com.xwy.lesson03;

import java.awt.*;

/**
 * @author levi
 * @create 2020/7/27 9:55 下午
 */
public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}
class MyPaint extends Frame{
    public void loadFrame(){
        setBounds(200,200,600,500);
        setVisible(true);
    }
    @Override
    public void paint(Graphics g) {
        //画笔需要有眼色
        g.setColor(Color.red);
        //y圆
        g.drawOval(300,300,100,100);
        g.fillOval(100,100,100,100);

        g.setColor(Color.green);
        g.fillRect(150,200,200,200);
        super.paint(g);
        //养成习惯,画笔用完还原最初的颜色
        
    }
}

2.8、鼠标监听

实现鼠标画画(点点)

package com.xwy.lesson03;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author levi
 * @create 2020/7/27 10:05 下午
 */
public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("画画");
    }
}
class MyFrame extends Frame{
    ArrayList points;
    //滑滑需要画笔,需要监听鼠标当前的位置,需要集合存储这个点
    public MyFrame(String title){
        super(title);
        setBounds(200,200,400,300);
        //村鼠标的点
        points = new ArrayList<>();
        //鼠标监听器,针对这个窗口
        this.addMouseListener(new MyMouseListener());
        setVisible(true);
    }
    @Override
    public void paint(Graphics g) {
        //监听鼠标事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point =  (Point)iterator.next();
            g.setColor(Color.red);
            g.fillOval(point.x,point.y,10,10);
        }
    }
    //添加一个点到界面上
    public void addPaint(Point point){
        points.add(point);
    }
    private class MyMouseListener  extends MouseAdapter{
        //鼠标按下、弹起、按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame myFrame = (MyFrame)e.getSource();
            //点击在界面产生一个点
            myFrame.addPaint(new Point(e.getX(),e.getY()));
            //每次点击鼠标都需要重新滑一次
            myFrame.repaint();
        }
    }
}

2.9、窗口监听

package com.xwy.lesson03;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author levi
 * @create 2020/7/27 10:28 下午
 */
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);
//        addWindowListener(new MyWindowsListener());
        //匿名内部类
        this.addWindowListener(
                new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent e) {
                        System.out.println("退出");
                        System.exit(0);//正常退出
                    }

                    @Override
                    public void windowActivated(WindowEvent e) {
                        System.out.println("显示");
                    }
                }
        );
    }

//    class MyWindowsListener extends WindowAdapter{
//        @Override
//        public void windowClosing(WindowEvent e) {
//            System.exit(0);//正常退出
//        }
//    }
}

3.0、键盘监听

package com.xwy.lesson03;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * @author levi
 * @create 2020/7/27 10:40 下午
 */
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();
                if(keycode == KeyEvent.VK_UP){
                    System.out.println("你按下了上键");
                }
            }
        });
    }
}

3、Swing

3.1、窗口、面板

package com.xwy.lesson04;

import javax.swing.*;

/**
 * @author levi
 * @create 2020/7/27 10:48 下午
 */
public class JFrameDemo {

    //初始化
    public void init(){
        JFrame jFrame = new JFrame("JFrame");
        jFrame.setBounds(100,100,400,400);
        //设置文字
        JLabel jLabel = new JLabel("xxxxxx");
        jFrame.add(jLabel);
        //关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }
    public static void main(String[] args) {
        //建立一个窗口
        new JFrameDemo().init();
    }
}

3.2、弹窗

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

package com.xwy.lesson04;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author levi
 * @create 2020/7/27 10:59 下午
 */
public class DialogDemo extends JFrame {
    public DialogDemo(){
        this.setSize(700,700);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);
        //JFrame 放东西 容器
        Container container = this.getContentPane();
        container.setLayout(null);
        JButton button = new JButton("弹出对话框");
        button.setBounds(20,20,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);
        Container container = this.getContentPane();
        container.setLayout(null);
        container.add(new Label("哈哈哈哈哈哈哈"));
    }
}

3.3、标签

label

new Label("title")

Swing- - JLabel

图标Icon

package com.xwy.lesson04;

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

/**
 * @author levi
 * @create 2020/7/27 11:18 下午
 */
public class IconDemo extends JFrame implements Icon {
    private int width;
    private int height;
    public IconDemo(){}
    public IconDemo(int width,int height){
        this.height = height;
        this.width = width;
    }
    public void init(){
        IconDemo iconDemo = new IconDemo(15,15);
        JLabel jLabel = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(jLabel);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,height);
    }

    @Override
    public int getIconWidth() {
        return 0;
    }

    @Override
    public int getIconHeight() {
        return 0;
    }


    public static void main(String[] args) {
        new IconDemo().init();
    }
}

图片Icon

package com.xwy.lesson04;

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

/**
 * @author levi
 * @create 2020/7/27 11:33 下午
 */
public class ImageIconDemo extends JFrame {

    public ImageIconDemo(){
        JLabel label = new JLabel("ImageIcon");
        URL url = ImageIconDemo.class.getResource("tx.jpg");

        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,300,300);
    }
    public static void main(String[] args) {
        new ImageIconDemo();
    }
}

3.4、面板

JPanel

package com.xwy.lesson05;

import com.xwy.lesson04.JFrameDemo;

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

/**
 * @author levi
 * @create 2020/7/28 11:15 上午
 */
public class JPanelDemo  extends JFrame {

    public JPanelDemo(){
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));//后面的参数是间距
        JPanel jPanel = new JPanel(new GridLayout(1,3));
        jPanel.add(new JButton("11111"));
        jPanel.add(new JButton("11111"));
        jPanel.add(new JButton("11111"));

        container.add(jPanel);

        this.setSize(500,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JPanelDemo();
    }
}

JScroll

package com.xwy.lesson05;

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

/**
 * @author levi
 * @create 2020/7/28 11:24 上午
 */
public class JScrollDemo extends JFrame {

    public JScrollDemo(){
        Container container = this.getContentPane();
        //文本域
        JTextArea jTextArea = new JTextArea(20, 50);
        jTextArea.setText("欢迎哈哈哈哈哈哈哈哈");
        //面板Scroll
        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        container.add(jScrollPane);
        this.setBounds(100,100,300,150);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollDemo();
    }
}

3.5、按钮

  • 图片按钮
package com.xwy.lesson05;

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

/**
 * @author levi
 * @create 2020/7/28 12:41 下午
 */
public class JButtonDemo01 extends JFrame {

    public JButtonDemo01(){
        Container container = getContentPane();
        URL url = JButtonDemo01.class.getResource("tx.jpg");
        Icon icon = new ImageIcon(url);

        //把图标放在按钮上
        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("图片按钮");
        container.add(button);
        this.setVisible(true);
        this.setSize(300,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo01();
    }
}
  • 单选按钮
package com.xwy.lesson05;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.net.URL;

/**
 * @author levi
 * @create 2020/7/28 12:47 下午
 */
public class JButtonDemo02 extends JFrame{
    public JButtonDemo02(){
        Container container = getContentPane();
        URL url = JButtonDemo01.class.getResource("tx.jpg");
        Icon icon = new ImageIcon(url);

        //单选框
        JRadioButton jRadioButton01 = new JRadioButton("JRadioButton1");
        JRadioButton jRadioButton02 = new JRadioButton("JRadioButton2");
        JRadioButton jRadioButton03 = new JRadioButton("JRadioButton3");

        //由于三个按钮不能被同时选中,分组
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton01);
        buttonGroup.add(jRadioButton02);
        buttonGroup.add(jRadioButton03);

        container.add(jRadioButton01, BorderLayout.CENTER);
        container.add(jRadioButton02,BorderLayout.NORTH);
        container.add(jRadioButton03,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setSize(300,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo02();
    }
}
  • 复选按钮
package com.xwy.lesson05;

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

/**
 * @author levi
 * @create 2020/7/28 12:52 下午
 */
public class JButtonDemo03 extends JFrame{
    public JButtonDemo03() {
        Container container = getContentPane();
        URL url = JButtonDemo03.class.getResource("tx.jpg");
        Icon icon = new ImageIcon(url);
        //多选框
        JCheckBox jCheckBox01 = new JCheckBox("checkbox01");
        JCheckBox jCheckBox02 = new JCheckBox("checkbox02");

        container.add(jCheckBox01,BorderLayout.NORTH);
        container.add(jCheckBox02,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setSize(300,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo03();
    }

}

3.6、列表

  • 下拉框
package com.xwy.lesson06;

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

/**
 * @author levi
 * @create 2020/7/28 12:58 下午
 */
public class TestComboboxDemo01 extends JFrame{
    public TestComboboxDemo01(){
        Container container = getContentPane();
        JComboBox status = new JComboBox();

        status.addItem(null);
        status.addItem("上映");
        status.addItem("下架");
        status.addItem("即将");
        container.add(status);

        this.setVisible(true);
        this.setSize(300,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestComboboxDemo01();
    }
}
  • 列表框
package com.xwy.lesson06;

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

/**
 * @author levi
 * @create 2020/7/28 1:01 下午
 */
public class TestComboboxDemo02 extends JFrame{
    public TestComboboxDemo02(){
        Container container = getContentPane();
//        String[] contents = {"1","2","3"};
        Vector contents = new Vector();
        JList jList = new JList(contents);
        container.add(jList);
        contents.add("qqq");
        contents.add("qqq");
        contents.add("qqq");

        this.setVisible(true);
        this.setSize(300,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestComboboxDemo02();
    }
}

应用场景

  • 选择地区或者一些单个选项
  • 列表用来展示信息,一般动态扩容

3.7、文本框

  • 文本框
package com.xwy.lesson06;

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

/**
 * @author levi
 * @create 2020/7/28 1:08 下午
 */
public class TextDemo01 extends JFrame {

    public TextDemo01(){
        Container container = getContentPane();

        JTextField textField = new JTextField("hello");
        JTextField textField2 = new JTextField("world");

        container.add(textField,BorderLayout.NORTH);
        container.add(textField2,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setSize(300,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TextDemo01();
    }
}
  • 密码框
package com.xwy.lesson06;/**
 * @author levi
 * @create 2020/7/28 1:12 下午
 */

import javafx.application.Application;
import javafx.stage.Stage;

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

public class TextDemo02 extends JFrame {

    public TextDemo02(){
        Container container = getContentPane();

        JPasswordField jPasswordField = new JPasswordField();
        jPasswordField.setEchoChar('*');
        container.add(jPasswordField);

        this.setVisible(true);
        this.setSize(300,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TextDemo02();
    }
}
  • 文本域

前面有了~

4、贪吃蛇

帧,时间片足够小,就是动画,一秒30帧,60帧,连起来是动画,拆开就是静态图片

键盘监听

定时器timer


StartGame.java启动类

package com.xwy.snake;

import javax.swing.*;

/**
 * @author levi
 * @create 2020/7/28 1:28 下午
 */
//游戏的启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setBounds(10,10,900,720);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //正常的游戏及=界面在面板上
        frame.add(new GamePanel());

        frame.setVisible(true);
    }
}

Data.java 数据中心

package com.xwy.snake;

import javax.swing.*;
import java.net.URL;

/**
 * @author levi
 * @create 2020/7/28 1:41 下午
 */
public class Data {

    public static URL headURL = Data.class.getResource("statics/header.png");
    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 header = new ImageIcon(headURL);
    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);
}

GamePanel.java

package com.xwy.snake;

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;

/**
 * @author levi
 * @create 2020/7/28 1:32 下午
 */
public class GamePanel extends JPanel implements KeyListener, ActionListener {
    //定义蛇的数据结构
    int length;
    int [] snake_x = new int[600];//x坐标
    int [] snake_y = new int[600];//y坐标
    String dir ;
    //游戏当前的状态:开始或者停止
    boolean isStart = false;//默认暂停
    boolean isFail = false;//游戏失败状态
    //食物的坐标
    int food_x;
    int food_y;
    Random random = new Random();
    int score;

    //定时器
    Timer timer = new Timer(100, this);//100ms执行一次定时器

    //构造器
    public GamePanel() {
        init();
        //获得焦点和键盘事件
        this.setFocusable(true);//获得焦点事件
        this.addKeyListener(this);//获得键盘监听事件
        timer.start();
    }
    //初始化
    public void init() {
        length = 3;
        snake_x[0] = 100;
        snake_y[0] = 100; //脑袋的坐标
        snake_x[1] = 75;
        snake_y[1] = 100; //第一个身体的坐标
        snake_x[2] = 50;
        snake_y[2] = 100; //第二个身体的坐标
        dir = "R";
        //让食物位置初始化
        food_x=25 + 25*random.nextInt(34);
        food_y=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, food_x, food_y);

        //把小蛇画上去
        if(dir.equals("R")){
            Data.right.paintIcon(this, g, snake_x[0],snake_y[0]);
        }else if(dir.equals("L")){
            Data.left.paintIcon(this, g, snake_x[0],snake_y[0]);
        }if(dir.equals("U")){
            Data.up.paintIcon(this, g, snake_x[0],snake_y[0]);
        }if(dir.equals("D")){
            Data.down.paintIcon(this, g, snake_x[0],snake_y[0]);
        }
        for(int i=1 ; i < length ; i++){
            Data.body.paintIcon(this, g, snake_x[i],snake_y[i]);
        }
        //游戏状态
        if(!isStart){
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("按下空格开始游戏",300,300);
        }
        //游戏状态
        if(!isStart){
            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 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){
            dir="U";
        }else if (keyCode==KeyEvent.VK_DOWN){
            dir="D";
        }else if (keyCode==KeyEvent.VK_LEFT){
            dir="L";
        }else if (keyCode==KeyEvent.VK_RIGHT){
            dir="R";
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {
    }
    @Override
    public void keyTyped(KeyEvent e) {
    }

    //事件监听--需要
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && !isFail){
            //吃食物
            if (snake_x[0]==food_x&&snake_y[0]==food_y){
                length++;
                //再次随机食物
                score+=10;
                food_x=25 + 25*random.nextInt(34);
                food_y=75 + 25*random.nextInt(24);
            }

            //移动
            for (int i = length-1; i >0;i--){
                snake_x[i]=snake_x[i-1];//向前移动一节
                snake_y[i]=snake_y[i-1];
            }

            if(dir.equals("R")){
                snake_x[0]=snake_x[0]+25;
                if(snake_x[0]>850){ snake_x[0]=25; }
            }else if (dir.equals("L")){
                snake_x[0]=snake_x[0]-25;
                if(snake_x[0]<25){ snake_x[0]=850; }
            }else if (dir.equals("U")){
                snake_y[0]=snake_y[0]-25;
                if(snake_y[0]<75){ snake_y[0]=650; }
            }else if (dir.equals("D")){
                snake_y[0]=snake_y[0]+25;
                if(snake_y[0]>650){ snake_y[0]=75; }
            }

            repaint();
        }
        //失败判断
        for (int i=1;i<length;i++){
            if (snake_x[0]==snake_x[i] && snake_y[0]==snake_y[i]){
                isFail=true;
            }
        }

        timer.start();//定时器开始
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值