GUI编程学习

一、简介

Gui的核心技术:Swing AWT

缺点:

​ 1.因为界面不美观

​ 2.需要jre环境!

为什么我们要学习?

​ 1.可以写出自己心中想要的一些小工具

​ 2.工作时候,也可能需要维护到swing界面,概率极小!

​ 3.了解MVC架构,了解监听!

二、AWT

2.1介绍

1.包含了很多类和接口!GUI

2.元素:窗口,按钮,文本框

3.java.awt

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ahv6G8su-1613141979881)(Gui.assets/image-20210212183358682.png)]

2.2组件和容器

1.Frame

package com.lesson01;

import java.awt.*;

/**
 * @description: GUI的第一个界面
 * @author: jyf
 * @create: 2021-02-12 14:09
 **/
public class TestFrame01 {
    public static void main(String[] args) {
        // Frame jdk 窗口
        Frame frame = new Frame("我的第一个java图形界面");

        // 弹出的初始位置
        frame.setLocation(200, 200);
        // 设置窗口可见
        frame.setSize(400, 400);

        // 设置背景颜色 Color
        frame.setBackground(new Color(212, 68, 43));

        // 设置大小固定
        frame.setResizable(false);
        // 设置窗口可见
        frame.setVisible(true);
    }
}
package com.lesson01;

import java.awt.*;

/**
 * @description: 尝试设置多个窗口,继承Frame,利用封装。写个方法,然后调用类创建
 * @author: jyf
 * @create: 2021-02-12 14:09
 **/
public class TestFrame02 {
    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.YELLOW);
        MyFrame myFrame3 = new MyFrame(100,300,200,200,Color.RED);
        MyFrame myFrame4 = new MyFrame(300,300,200,200,Color.GREEN);

    }
}
class MyFrame extends Frame {
    static int id = 0; // 可能存在多个窗口,需要一个计数器
    public MyFrame(int x, int y, int w, int h, Color color) {
        super("MyFrame" + (++id));
        setBounds(x, y, w, h);
        setBackground(color);
        setResizable(false);
        setVisible(true);
    }
}

2.面板Panel

package com.lesson01;

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

/**
 * @description: Panel 可以看成是一个空间,但是不能独立存在 面板
 * @author: jyf
 * @create: 2021-02-12 14:27
 **/
public class TestPanel {

    public static void main(String[] args) {
        Frame frame = new Frame();
        Panel panel = new Panel();
        // 设置布局
        panel.setLayout(null);
        // 坐标
        frame.setBounds(300, 300, 500, 500);
        frame.setBackground(new Color(94, 233, 30));
        // panel设置坐标
        panel.setBounds(10, 10, 10, 10);
        panel.setBackground(new Color(215, 38, 28));
        // frame
        frame.add(panel);
        frame.setVisible(true);
        
        //监听事件监听窗口关闭System.exit(0)
        //适配器模式 WindowListener
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

2.3布局管理器

  • 流式布局 FlowLayout

    package com.lesson01;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    /**
     * @description:
     * @author: jyf
     * @create: 2021-02-12 14:45
     **/
    public class TestFlowLayout {
        public static void main(String[] args) {
            Frame frame = new Frame();
    
            // 组件-按钮
            Button button01 = new Button("button01");
            Button button02 = new Button("button02");
            Button button03 = new Button("button03");
            Button button04 = new Button("button04");
    
            // 设置为流式布局
    //        frame.setLayout(new FlowLayout());
    //        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
            frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
    
            frame.setSize(500,500);
            // 添加按钮
            frame.add(button01);
            frame.add(button02);
            frame.add(button03);
            frame.add(button04);
    
            frame.setVisible(true);
    
            //监听事件监听窗口关闭System.exit(0)
            //适配器模式 WindowListener
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    
    
  • 东西南北中 BorderLayout

    package com.lesson01;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    /**
     * @description: 东西南北中
     * @author: jyf
     * @create: 2021-02-12 14:45
     **/
    public class TestBoderLayout {
        public static void main(String[] args) {
            Frame frame = new Frame("BoderLayout");
    
            // 组件-按钮
            Button east = new Button("east");
            Button west = new Button("west");
            Button south = new Button("south");
            Button north = new Button("north");
            Button center = new Button("center");
    
            // 设置为流式布局
            frame.setLayout(new BorderLayout());
    
            frame.setSize(500,500);
            // 添加按钮
            frame.add(east,BorderLayout.EAST);
            frame.add(west,BorderLayout.WEST);
            frame.add(south,BorderLayout.SOUTH);
            frame.add(north,BorderLayout.NORTH);
            frame.add(center,BorderLayout.CENTER);
    
            frame.setVisible(true);
    
            //监听事件监听窗口关闭System.exit(0)
            //适配器模式 WindowListener
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    
    
  • 表格布局 GridLayout

    package com.lesson01;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    /**
     * @description: 表格布局
     * @author: jyf
     * @create: 2021-02-12 14:45
     **/
    public class TestGridLayout {
        public static void main(String[] args) {
            Frame frame = new Frame("GridLayout");
    
            // 组件-按钮
            Button btn1 = new Button("btn1");
            Button btn2 = new Button("btn2");
            Button btn3 = new Button("btn3");
            Button btn4 = new Button("btn4");
            Button btn5 = new Button("btn5");
            Button btn6 = new Button("btn6");
    
            // 设置为流式布局
            frame.setLayout(new GridLayout(3,2));
    
            frame.setSize(500,500);
            // 添加按钮
            frame.add(btn1);
            frame.add(btn2);
            frame.add(btn3);
            frame.add(btn4);
            frame.add(btn5);
            frame.add(btn6);
    
            frame.pack(); // java函数自动填充
            frame.setVisible(true);
    
            //监听事件监听窗口关闭System.exit(0)
            //适配器模式 WindowListener
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    
    

练习

在这里插入图片描述

package com.lesson01;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 15:06
 **/
public class ExDemo {

    public static void main(String[] args) {
        Frame frame = new Frame("练习");
        frame.setSize(500, 500);
        frame.setLocation(200, 200);

        frame.setLayout(new GridLayout(2, 1));

        Panel p1 = new Panel(new BorderLayout());
        Panel p2 = new Panel(new GridLayout(2, 1));
        Panel p3 = new Panel(new BorderLayout());
        Panel p4 = new Panel(new GridLayout(2, 2));

        // 上面的
        p1.add(new Button("p1-WEST"), BorderLayout.WEST);
        p1.add(new Button("p1-EAST"), BorderLayout.EAST);
        p2.add(new Button("p2-1"));
        p2.add(new Button("p2-2"));
        p1.add(p2, BorderLayout.CENTER);

        // 下面
        p3.add(new Button("p3-WEST"), BorderLayout.WEST);
        p3.add(new Button("p3-EAST"), BorderLayout.EAST);
        for (int i = 0; i < 4; i++) {
            p4.add(new Button("p3-" + (i + 1)));
        }
        p3.add(p4, BorderLayout.CENTER);

        frame.add(p1);
        frame.add(p3);

//        frame.pack(); // java函数自动填充
        frame.setVisible(true);
        //监听事件监听窗口关闭System.exit(0)
        //适配器模式 WindowListener
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

总结:

  1. Frame是一个顶级窗口
  2. Paner无法单独显示,必须添加到某个容器中。
  3. 布局管理器
    1. 流式
    2. 东南西北
    3. 表格
  4. 大小,定位,背景颜色,可见性,监听。

2.4事件监听

package com.lesson02;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 15:27
 **/
public class TestActionEvent {
    public static void main(String[] args) {
        // 按下按钮的时候,触发一些事件
        Frame frame = new Frame("开始-停止");
        Button button01 = new Button("start");
        Button button02 = new Button("stop");

        button01.setActionCommand("start");

        MyActionListener myActionListener = new MyActionListener();
        button01.addActionListener(myActionListener);
        button02.addActionListener(myActionListener);

        frame.add(button01,BorderLayout.NORTH);
        frame.add(button02,BorderLayout.SOUTH);

        frame.setBounds(300, 300, 500, 500);
        frame.setVisible(true);
        closeWindow(frame);
    }

    public static void closeWindow(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(e.getActionCommand());
    }
}

2.5输入框TextField的监听事件

package com.lesson02;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 15:48
 **/
public class TestText01 {
    public static void main(String[] args) {
        // 启动
        new MyFrame();
    }
}

class MyFrame extends Frame {
    public MyFrame() {
        TextField textField = new TextField();
        add(textField);
        MyActionListener01 myActionListener = new MyActionListener01();
        textField.addActionListener(myActionListener);

        // 设置替换编码
        textField.setEchoChar('*');

        setVisible(true);
        setBounds(200, 200, 500, 500);
//        pack();
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyActionListener01 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField textField = (TextField) e.getSource();// 获得一些资源,返回一个对象
        System.out.println(textField.getText());
        textField.setText("");
    }
}

2.6.简易计算器

组合+内部类回顾

oop原则:组合,大于继承!

package com.lesson02;

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

/**
 * @description: 简易计算器
 * @author: jyf
 * @create: 2021-02-12 16:07
 **/
public class TestCalc {
    public static void main(String[] args) {
        new Calculator();
    }
}

// 计算器类
class Calculator extends Frame {

    public Calculator() {
        // 3个文本框 1个按钮= 1个标签+
        TextField num1 = new TextField(10); // 字符数
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(20);

        Button btn1 = new Button("=");
        btn1.addActionListener(new MyCalculatorActionListener(num1, num2, num3));

        Label label = new Label("+");

        // 布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(btn1);
        add(num3);

        pack();
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

// 监听器类
class MyCalculatorActionListener implements ActionListener {

    private TextField num1;
    private TextField num2;
    private TextField num3;

    public MyCalculatorActionListener(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.lesson02;

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

/**
 * @description: 简易计算器
 * @author: jyf
 * @create: 2021-02-12 16:07
 **/
public class TestCalc {
    public static void main(String[] args) {
        new Calculator();
    }
}

// 计算器类
class Calculator extends Frame {

    TextField num1;
    TextField num2;
    TextField num3;

    public Calculator() {
        // 3个文本框 1个按钮= 1个标签+
        num1 = new TextField(10); // 字符数
        num2 = new TextField(10);
        num3 = new TextField(20);

        Button btn1 = new Button("=");
        btn1.addActionListener(new MyCalculatorActionListener(this));

        Label label = new Label("+");

        // 布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(btn1);
        add(num3);

        pack();
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

// 监听器类
class MyCalculatorActionListener implements ActionListener {
	//获取计算器对象 在一个类中组合另外一个类
    private Calculator calculator;

    public MyCalculatorActionListener(Calculator calculator) {
        this.calculator = calculator;

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // 获得两个加数
        int n1 = Integer.parseInt(calculator.num1.getText());
        int n2 = Integer.parseInt(calculator.num2.getText());

        calculator.num3.setText("" + (n1 + n2));

        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}

内部类 – 内部类最大特点:可以畅通无阻的访问外部类的方法,属性

package com.lesson02;

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

/**
 * @description: 简易计算器
 * @author: jyf
 * @create: 2021-02-12 16:07
 **/
public class TestCalc {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

// 计算器类
class Calculator extends Frame {

    TextField num1;
    TextField num2;
    TextField num3;

    public void loadFrame(){
        // 3个文本框 1个按钮= 1个标签+
        num1 = new TextField(10); // 字符数
        num2 = new TextField(10);
        num3 = new TextField(20);

        Button btn1 = new Button("=");
        btn1.addActionListener(new MyCalculatorActionListener());

        Label label = new Label("+");

        // 布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(btn1);
        add(num3);

        pack();
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    // 监听器类
    private class MyCalculatorActionListener 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.lesson03;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 16:37
 **/
public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}

class MyPaint extends Frame {

    public void loadFrame() {
        setBounds(200, 200, 500, 500);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    @Override
    public void paint(Graphics g) { // 画笔 画画
        g.setColor(Color.RED);
        g.drawOval(100,100,100,100); // 画圆
        g.fillOval(100,100,100,100); // 画实心圆

        g.setColor(Color.GREEN);
        g.fillRect(150,200,100,100); // 画矩形
        //画笔用完,将他还原到最初的颜色
    }
}

2.8鼠标监听

package com.lesson03;

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

/**
 * @description: 鼠标监听
 * @author: jyf
 * @create: 2021-02-12 16:45
 **/
public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("画画");
    }
}

//自己的类
class MyFrame extends Frame {
    //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
    ArrayList<Point> points;

    public MyFrame(String title) {
        super(title);

        points = new ArrayList<>();
        addMouseListener(new MyMouseListener());

        setBounds(200, 200, 500, 500);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    @Override
    public void paint(Graphics g) {
        // 画画,监听鼠标监听器
        g.setColor(Color.BLUE);
        Iterator<Point> iterator = points.iterator();
        while (iterator.hasNext()) {
            Point next = iterator.next();
            g.fillOval(next.x, next.y, 10, 10);
        }
    }

    private class MyMouseListener extends MouseAdapter {
        //鼠标按下,弹起,按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame frame = (MyFrame) e.getSource();
            //我们点击的时候,就会在界面上产生一个点! 这个点就是鼠标的点:
            frame.points.add(new Point(e.getX(), e.getY()));
            //每次点击鼠标都需要重新画一遍
            frame.repaint(); //刷新
        }
    }
}

2.9窗口监听

package com.lesson03;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 17:11
 **/
public class TestWindowListener {
    public static void main(String[] args) {
        new WindowFrame();
    }
}

class WindowFrame extends Frame {
    public WindowFrame() {
        setBackground(Color.GREEN);
        setBounds(100, 100, 200, 200);
        setVisible(true);

        addWindowListener(new WindowAdapter() {
            //关闭窗口
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }

            //激活窗口
            @Override
            public void windowActivated(WindowEvent e) {
                WindowFrame source = (WindowFrame) e.getSource();
                source.setTitle("已激活");
                System.out.println("windowActivated");
            }
        });
    }
}

2.10键盘监听

package com.lesson03;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 17:15
 **/
public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame{
    public KeyFrame() {

        setBounds(200, 200, 500, 500);
        setVisible(true);

        addKeyListener(new KeyAdapter() {
            // 键盘按下
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                System.out.println("keyCode = " + keyCode);
                if(keyCode == KeyEvent.VK_UP){
                    System.out.println("你按了上建");
                }
            }
        });


        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

三、Swing

Swing是amt的封装演化,

3.1窗口、面板 JFrame Container

package com.lesson04;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 17:27
 **/
public class JFrameDemo {
    public static void main(String[] args) {
        // 建立一个窗口
        new MyJFrame().initJFrame();
    }
}
class MyJFrame extends JFrame{

    public void initJFrame(){

        JLabel jLabel = new JLabel("---------JLabel-----------");
        jLabel.setHorizontalAlignment(SwingConstants.CENTER); // 设置水平对齐 文字居中
        this.add(jLabel);

        Container contentPane = this.getContentPane();
        contentPane.setBackground(Color.blue);

        this.setTitle("这是一个JFrame窗口");
        this.setVisible(true);
        this.setBounds(200,200,500,500);
        // 关闭事件   EXIT_ON_CLOSE HIDE_ON_CLOSE DISPOSE_ON_CLOSE DO_NOTHING_ON_CLOSE
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3.2弹窗 JDialog

package com.lesson04;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 17:48
 **/
public class DialogDemo extends JFrame {

    public static void main(String[] args) {
        new DialogDemo();
    }

    public DialogDemo() {
        Container contentPane = this.getContentPane(); // JFrame容器
        contentPane.setLayout(null);// 绝对布局

        // 按钮
        JButton jButton = new JButton("点击弹出一个对话框");
        jButton.setBounds(30,30,200,50);

        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 弹窗
                MyDialog myDialog = new MyDialog();
                System.out.println(myDialog);
            }
        });

        contentPane.add(jButton);

        this.setVisible(true);
        this.setBounds(200,200,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
// 弹窗
class MyDialog extends JDialog{
    public MyDialog() {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(null);
        contentPane.add(new JLabel("-----MyDialog------"));

        this.setVisible(true);
        this.setBounds(250,250,400,400);
        // DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, or DISPOSE_ON_CLOSE
        // this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3.3标签 图标 JLabel Icon

package com.lesson04;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 18:07
 **/
public class IconDemo extends JFrame {
    public static void main(String[] args) {
        new IconDemo();
    }

    public IconDemo() {
        MyIcon myIcon = new MyIcon(15, 15);
        JLabel jLabel = new JLabel("icon_test", myIcon, SwingConstants.CENTER);

        Container contentPane = this.getContentPane();
        contentPane.add(jLabel);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

class MyIcon implements Icon {

    private int width;
    private int height;

    public MyIcon(int width, int height) {
        this.width = width;
        this.height = height;
    }

    @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;
    }
}
package com.lesson04;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 18:27
 **/
public class ImageIconDemo extends JFrame {
    public static void main(String[] args) {
        new ImageIconDemo();
    }

    public ImageIconDemo() {
        JLabel jLabel = new JLabel("imageIcon");
        URL url = ImageIconDemo.class.getResource("1.png");
        ImageIcon imageIcon = new ImageIcon(url);
        jLabel.setIcon(imageIcon);
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);

        Container contentPane = this.getContentPane();
        contentPane.add(jLabel);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3.4面板 JPanel JScrollPane

package com.lesson05;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 18:43
 **/
public class JPanelDemo extends JFrame {
    public static void main(String[] args) {
        new JPanelDemo();
    }

    public JPanelDemo() {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new GridLayout(2,1,10,10));

        JPanel jPanel1 = new JPanel(new GridLayout(1,3));
        JPanel jPanel2 = new JPanel(new GridLayout(1,2));
        JPanel jPanel3 = new JPanel(new GridLayout(2,1));
        JPanel jPanel4 = new JPanel(new GridLayout(3,2));

        jPanel1.add(new JButton("1"));
        jPanel1.add(new JButton("1"));
        jPanel1.add(new JButton("1"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel3.add(new JButton("3"));
        jPanel3.add(new JButton("3"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));

        contentPane.add(jPanel1);
        contentPane.add(jPanel2);
        contentPane.add(jPanel3);
        contentPane.add(jPanel4);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

package com.lesson05;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 19:16
 **/
public class JScrollDemo extends JFrame {
    public static void main(String[] args) {
        new JScrollDemo();
    }

    public JScrollDemo() {
        Container contentPane = this.getContentPane();

        // 文本域
        JTextArea jTextArea = new JTextArea(20,50);
        jTextArea.setText("-------------------");
        // Scroll面板
        JScrollPane jScrollPane = new JScrollPane(jTextArea);

        contentPane.add(jScrollPane);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3.5按钮 JButton JRadioButton JCheckBox

package com.lesson05;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 19:52
 **/
public class JButtonDemo01 extends JFrame {
    public static void main(String[] args) {
        new JButtonDemo01();
    }

    public JButtonDemo01() {
        Container contentPane = this.getContentPane();

        URL resource = JButtonDemo01.class.getResource("1.png");
        Icon icon = new ImageIcon(resource);

        JButton jButton = new JButton("jay");
        jButton.setIcon(icon);
        jButton.setToolTipText("这是一个图片按钮");

        contentPane.add(jButton);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

  • 单选按钮
package com.lesson05;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 19:52
 **/
public class JButtonDemo02 extends JFrame {
    public static void main(String[] args) {
        new JButtonDemo02();
    }

    public JButtonDemo02() {
        Container contentPane = this.getContentPane();
        
        // 单选框
        JRadioButton jRadioButton1 = new JRadioButton("jRadioButton1");
        JRadioButton jRadioButton2 = new JRadioButton("jRadioButton2");
        JRadioButton jRadioButton3 = new JRadioButton("jRadioButton3");

        // 单选框只能选择一个 一个组只能选一个
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);
        buttonGroup.add(jRadioButton3);

        contentPane.add(jRadioButton1,BorderLayout.NORTH);
        contentPane.add(jRadioButton2,BorderLayout.CENTER);
        contentPane.add(jRadioButton3,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

  • 复选按钮
package com.lesson05;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 19:52
 **/
public class JButtonDemo03 extends JFrame {
    public static void main(String[] args) {
        new JButtonDemo03();
    }

    public JButtonDemo03() {
        Container contentPane = this.getContentPane();

        // 多选框
        JCheckBox jCheckBox1 = new JCheckBox("jRadioButton1");
        JCheckBox jCheckBox2 = new JCheckBox("jRadioButton2");
        JCheckBox jCheckBox3 = new JCheckBox("jRadioButton3");

        contentPane.add(jCheckBox1,BorderLayout.NORTH);
        contentPane.add(jCheckBox2,BorderLayout.CENTER);
        contentPane.add(jCheckBox3,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3.6列表 JComboBox

  • 下拉框 JComboBox
package com.lesson06;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 20:09
 **/
public class TestComboboxDemo01 extends JFrame {
    public static void main(String[] args) {
        new TestComboboxDemo01();
    }

    public TestComboboxDemo01() {
        Container contentPane = this.getContentPane();

        // 下拉框
        JComboBox jComboBox = new JComboBox();
        jComboBox.addItem("1");
        jComboBox.addItem("2");
        jComboBox.addItem("3");
        jComboBox.addItem("4");

        contentPane.add(jComboBox);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

  • 列表框
package com.lesson06;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 20:09
 **/
public class TestComboboxDemo02 extends JFrame {
    public static void main(String[] args) {
        new TestComboboxDemo02();
    }

    public TestComboboxDemo02() {
        Container contentPane = this.getContentPane();

        // 生成列表的内容
//        String[] contents = {"1","2","3"};
        Vector contents = new Vector();
        contents.add("jay01");
        // 列表需要放的内容
        JList jList = new JList(contents);
        contents.add("jay02");
        contents.add("jay03");

        contentPane.add(jList);
        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

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

3.7文本框

  • 文本框
package com.lesson06;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 20:09
 **/
public class TestTextDemo01 extends JFrame {
    public static void main(String[] args) {
        new TestTextDemo01();
    }

    public TestTextDemo01() {
        Container contentPane = this.getContentPane();

        JTextField jTextField1 = new JTextField("hello");
        JTextField jTextField2 = new JTextField("world",20);

        contentPane.add(jTextField1,BorderLayout.NORTH);
        contentPane.add(jTextField2,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

  • 密码框
package com.lesson06;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 20:09
 **/
public class TestTextDemo02 extends JFrame {
    public static void main(String[] args) {
        new TestTextDemo02();
    }

    public TestTextDemo02() {
        Container contentPane = this.getContentPane();

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

        contentPane.add(jPasswordField);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

  • 文本域
package com.lesson05;

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

/**
 * @description:
 * @author: jyf
 * @create: 2021-02-12 19:16
 **/
public class JScrollDemo extends JFrame {
    public static void main(String[] args) {
        new JScrollDemo();
    }

    public JScrollDemo() {
        Container contentPane = this.getContentPane();

        // 文本域
        JTextArea jTextArea = new JTextArea(20,50);
        jTextArea.setText("-------------------");
        // Scroll面板
        JScrollPane jScrollPane = new JScrollPane(jTextArea);

        contentPane.add(jScrollPane);

        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

贪吃蛇

帧,如果时间片足够小,就是动画 一秒三石帧,连起来是动画 拆开就是图片

键盘监听 addKeyListener

需要注意 如果是面板添加监听需要设置当前面板获取焦点setFocusable(true);

定时器Timer


package com.snake;

import javax.swing.*;

/**
 * @description: 窗口
 * @author: jyf
 * @create: 2021-02-12 20:32
 **/
public class StartGame {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame();

        // 正常的游戏界面都应该在面板上
        jFrame.add(new GamePanel());

        jFrame.setResizable(false);// 窗口大小不可变
        jFrame.setBounds(10,10,900,720);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

package com.snake;

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

/**
 * @description: 数据中心
 * @author: jyf
 * @create: 2021-02-12 20:40
 **/
public class Data {
    /*
    相对路径
    绝对路径 / 相当于当前项目
    */

    //头部图片
    public static URL headerUrl = Data.class.getResource("/static/header.png");

    public static ImageIcon header = new ImageIcon(headerUrl);

    //头部:上下左右
    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 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("/static/body.png");

    public static ImageIcon body = new ImageIcon(bodyUrl);

    //食物
    public static URL foodUrl = Data.class.getResource("/static/food.png");

    public static ImageIcon food = new ImageIcon(foodUrl);
}

package com.snake;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;

/**
 * @description: 游戏的面板
 * @author: jyf
 * @create: 2021-02-12 20:34
 **/
public class GamePanel extends JPanel {

    // 定义蛇的数据结构
    int length;// 蛇的长度
    int[] snakeX = new int[600]; // 蛇的x坐标
    int[] snakeY = new int[600]; // 蛇的y坐标
    String direction; // 方向

    // 游戏当前状态默认未开始
    boolean isStart = false;

    //定时器 以毫秒为单位 1000ms = 1s
    Timer timer = new Timer(100, new SnakeActionListener()); // 100毫秒执行一次

    // 食物的坐标
    int foodx;
    int foody;
    Random random = new Random();

    boolean isFail = false; //游戏是否结束

    int score;

    // 构造器
    public GamePanel() {
        init();

        // 获得焦点和键盘事件
        this.setFocusable(true); // 焦点事件
        this.addKeyListener(new SnakeKeyListener());// 键盘事件
        timer.start();
    }

    public void init() {
        // 初始化蛇
        length = 3;      // 蛇的长度 初始化3

        snakeX[0] = 100; // 脑袋的坐标
        snakeY[0] = 100; // 脑袋的坐标
        snakeX[1] = 75;  // 第一个身体的坐标
        snakeY[1] = 100; // 第一个身体的坐标
        snakeX[2] = 50;  // 第二个身体的坐标
        snakeY[2] = 100; // 第二个身体的坐标

        direction = "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); // 默认的游戏界面

        // 食物
        Data.food.paintIcon(this, g, foodx, foody);

        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑", Font.BOLD, 18));
        g.drawString("长度 " + length, 750, 35);
        g.drawString("分数 " + score, 750, 50);

        // 把小蛇画上去
        switch (direction) {
            case "R":
                Data.right.paintIcon(this, g, snakeX[0], snakeY[0]); // 蛇头 向右
                break;
            case "L":
                Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);  // 蛇头 向左
                break;
            case "U":
                Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);  // 蛇头 向上
                break;
            case "D":
                Data.down.paintIcon(this, g, snakeX[0], snakeY[0]);  // 蛇头 向下
                break;
        }

        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this, g, snakeX[i], snakeY[i]);  // 身体的坐标
        }

        // 游戏状态
        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);
        }
    }

    // 键盘监听器
    class SnakeKeyListener extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode(); // 获得键盘按键是哪一个
            switch (keyCode) {
                case KeyEvent.VK_SPACE:   // 空格键
                    if (isFail) { // 游戏失败
                        isFail = false; // 重置游戏状态
                        init();
                    } else {  // 暂停 开始
                        isStart = !isStart;
                    }
                    repaint();  // 重画
                    break;
                // 小蛇移动
                case KeyEvent.VK_UP:   // 上键
                    if(direction == "D"){ // 不能倒退
                        break;
                    }
                    direction = "U";
                    repaint();  // 重画
                    break;
                case KeyEvent.VK_DOWN:   // 下键
                    if(direction == "U"){
                        break;
                    }
                    direction = "D";
                    repaint();  // 重画
                    break;
                case KeyEvent.VK_LEFT:   // 左键
                    if(direction == "R"){ // 不能倒退
                        break;
                    }
                    direction = "L";
                    repaint();  // 重画
                    break;
                case KeyEvent.VK_RIGHT:   // 右键
                    if(direction == "L"){ // 不能倒退
                        break;
                    }
                    direction = "R";
                    repaint();  // 重画
                    break;
            }
        }
    }

    // 事件监听 -- 需要固定事件来刷新,1s=10次
    class SnakeActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (isStart && !isFail) { // 如果游戏是开始状态 and 未失败,就让小蛇动起来
                // 吃到食物了
                if (snakeX[0] == foodx && snakeY[0] == foody) {
                    length++;// 长度 +1
                    score = score + 10;// 增加积分
                    // 重新生成随机食物
                    foodx = 25 + 25 * random.nextInt(34);
                    foody = 75 + 25 * random.nextInt(24);

                    /*if(score > 20){
                        timer.setDelay(10);
                    }*/
                }

                // 蛇身体向前进1
                for (int i = length - 1; i > 0; i--) {
                    snakeX[i] = snakeX[i - 1];
                    snakeY[i] = snakeY[i - 1];
                }

                // 头部判断上下左右
                switch (direction) {
                    case "R": // 向右
                        snakeX[0] = snakeX[0] + 25;
                        if (snakeX[0] > 850) { // 边界判断
                            snakeX[0] = 25;
                        }
                        break;
                    case "L": // 向左
                        snakeX[0] = snakeX[0] - 25;
                        if (snakeX[0] < 25) { // 边界判断
                            snakeX[0] = 850;
                        }
                        break;
                    case "U": // 向上
                        snakeY[0] = snakeY[0] - 25;
                        if (snakeY[0] < 75) { // 边界判断
                            snakeY[0] = 650;
                        }
                        break;
                    case "D": // 向下
                        snakeY[0] = snakeY[0] + 25;
                        if (snakeY[0] > 650) { // 边界判断
                            snakeY[0] = 75;
                        }
                        break;
                }

                // 结束判断,头和身体撞到了
                for (int i = 1; i < length; i++) {
                    if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                        isFail = true;
                    }
                }
                repaint(); // 重画界面
            }
        }
    }
    
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值