JAVA SE基础笔记(四)-re


JAVA-GUI编程 笔记

  • 1.简介
  • 2、AWT
    • 2.1、实现如图1-2
      • (1)面向过程写法
      • (2)内部类写法
      • (3)完全改造成面向对象
  • 3、Swing
    • 3.1、鼠标花点
    • 3.2、弹窗
    • 3.3、标签(Icon和ImageIcon)
    • 3.4、JScroll面板
    • 3.5、JButton(单选框、复选框)
      • 3.5.1、单选框
      • 3.5.2、复选框
  • 4、贪吃蛇

AWT

面向过程写法

package 寒假训练.狂神.GUI;

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

public class TestCul {
    public static void main(String[] args) {
        new Calculator();
    }
}

class Calculator extends Frame{
    TextField num1,num2,num3;
    public Calculator(){
        //创建三个文本框
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(20);
        Button button = new Button("=");
        Label label = new Label("+");

        //创建事件监听器
        buttonActionListener listener = new buttonActionListener(num1,num2,num3);
        button.addActionListener(listener);

        //布局
        setLayout(new FlowLayout(10));
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setSize(480,70);
        setBackground(new Color(255,213,123));
        //监听鼠标事件,关闭frame
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        setVisible(true);
    }
}

class buttonActionListener implements ActionListener{
    TextField num1,num2,num3;

    public buttonActionListener(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("");
    }
}

(2)内部类写法

package 寒假训练.狂神.GUI;

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

public class TestCul {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

class Calculator 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("=");
        Label label = new Label("+");

        //创建事件监听器
        buttonActionListener listener = new buttonActionListener();
        button.addActionListener(listener);

        //布局
        setLayout(new FlowLayout(10));
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setSize(480,70);
        setBackground(new Color(255,213,123));
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        setVisible(true);
    }
    
    private class buttonActionListener 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("");
        }
    }
}

(3)完全改造成面向对象

package 寒假训练.狂神.GUI;

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

public class TestCul {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

class Calculator 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("=");
        Label label = new Label("+");

        //创建事件监听器
        buttonActionListener listener = new buttonActionListener(this);
        button.addActionListener(listener);

        //布局
        setLayout(new FlowLayout(10));
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setSize(480,70);
        setBackground(new Color(255,213,123));
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        setVisible(true);
    }
}
class buttonActionListener implements ActionListener{
  
    Calculator calculator ;
    public buttonActionListener(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("");
    }
}

3、Swing

3.1、鼠标花点

在这里插入图片描述

package 寒假训练.狂神.GUI;

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

/*
创建鼠标监听事件
 */
public class TestMouseLisenter {
    public static void main(String[] args) {
        new MouseFrame("画花");
    }
}

//自己的类
class MouseFrame extends Frame{
    ArrayList points;
    //画花需要画笔,需要监听鼠标的位置,需要用集合来存
    public MouseFrame(String title){
        super(title);
        setBounds(200,200,400,300);
        //存鼠标点击这个点
        points = new ArrayList<>();
        //鼠标监听器
        this.addMouseListener(new MyMouseListener());
        setVisible(true);
        //关闭界面
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    @Override
    public void paint(Graphics g) {
        //画画,监听鼠标事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point = (Point)iterator.next();
            g.setColor(Color.green);
            g.fillOval(point.x,point.y,10,10);
        }
    }
    //添加一个点
    public void addPoint(Point point){
        points.add(point);
    }

    /*
    采用了适配器模式
    因为 MouseLisenter是一个接口,不需要实现里边的全部接口
     */
    private class MyMouseListener extends MouseAdapter {
        //鼠标的事件有,按下、弹起、按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MouseFrame source =(MouseFrame)e.getSource();
            //这个点我们在点击时,就会在界面上
            //这个点就是鼠标上的点
            source.addPoint(new Point(e.getX(),e.getY()));
            //每次重新画一遍,就是刷新
            source.repaint();
        }
    }
}

3.2、弹窗

package 寒假训练.狂神.GUI;

//弹窗
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestDialog extends JFrame {
    public TestDialog() {
        this.setVisible(true);
        this.setBounds(100,100,500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //JFrame 放东西,容器
        Container container = this.getContentPane();
        container.setBackground(new Color(112, 179, 91));
        container.setLayout(null);

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

        //当点击这个按钮时弹出一个对话框
        jb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyDialog();
            }
        });

        container.add(jb);
    }

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

//弹出的对话框
class MyDialog extends JDialog {
    public MyDialog() {
        this.setVisible(true);
        this.setBounds(100,100,500,500);

        Container contentPane = this.getContentPane();
        contentPane.setLayout(null);

        JLabel label = new JLabel("老秦带你学Java");
        label.setBounds(100,100,200,100);
        label.setFont(new Font("黑体",2,20));
        contentPane.setBackground(Color.red);
        contentPane.add(label);
    }
}

3.3、标签(Icon和ImageIcon)

package 寒假训练.狂神.GUI;

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

public class TestImageIcon extends JFrame {

    public TestImageIcon() {
        JLabel label = new JLabel("ImageIcon");
        //当前这个类下边的图片地址
        URL url = TestImageIcon.class.getResource("3.jpg");

        ImageIcon icon = new ImageIcon(url);
        label.setIcon(icon);
        //居中
        label.setHorizontalAlignment(SwingConstants.CENTER);

        Container contentPane = getContentPane();
        contentPane.add(label);
        contentPane.setBackground(new Color(170, 255, 179));

        setBounds(100,100,500,400);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

3.4、JScroll面板

在这里插入图片描述

package 寒假训练.狂神.GUI;

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

public class TestJScrollDemo extends JFrame {
    public TestJScrollDemo(){
        Container contentPane = this.getContentPane();

        //文本域
        TextArea textArea = new TextArea(30,100);
        textArea.setText("欢迎学习秦老师说java");

        //滑动面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        contentPane.add(scrollPane);

        setBounds(100,100,500,400);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

3.5、JButton(单选框、复选框)

3.5.1、单选框

在这里插入图片描述

package 寒假训练.狂神.GUI;

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

public class TestJButton extends JFrame {
    public TestJButton() {
        Container contentPane = this.getContentPane();

        //单选框
        JRadioButton rediobutton1 = new JRadioButton("rediobutton1");
        JRadioButton rediobutton2 = new JRadioButton("rediobutton2");
        JRadioButton rediobutton3 = new JRadioButton("rediobutton3");

        //由于单选框只能选一个,分组,一个组里边只选一个
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(rediobutton1);
        buttonGroup.add(rediobutton2);
        buttonGroup.add(rediobutton3);

        contentPane.add(rediobutton1,BorderLayout.NORTH);
        contentPane.add(rediobutton2,BorderLayout.CENTER);
        contentPane.add(rediobutton3,BorderLayout.SOUTH);

        setVisible(true);
        setSize(400,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


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

3.5.2、复选框

在这里插入图片描述

package 寒假训练.狂神.GUI;

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

public class TestJButton extends JFrame {
    public TestJButton() {
        Container contentPane = this.getContentPane();

        //复选框
        JCheckBox checkBox1 = new JCheckBox("checkBox1");
        JCheckBox checkBox2 = new JCheckBox("checkBox2");
        JCheckBox checkBox3 = new JCheckBox("checkBox3");

        contentPane.add(checkBox1,BorderLayout.NORTH);
        contentPane.add(checkBox2,BorderLayout.CENTER);
        contentPane.add(checkBox3,BorderLayout.SOUTH);

        setVisible(true);
        setSize(400,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


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

4、贪吃蛇

我的素材是在阿里矢量图库里找的为32*32的,只有那个头是狂神的。
链接:https://pan.baidu.com/s/1RX_Ix-wsWDdRDAQvv2uULQ
提取码:leka
素材可以自己去阿里巴巴矢量图库去找:https://www.iconfont.cn/
狂神的原版素材:
链接:https://pan.baidu.com/s/13AUb-dErFOyiCKGriqhk7w
提取码:enz7

package 寒假训练.狂神.GUI.Snake;

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

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 ImageIcon up = new ImageIcon(upURL);
    public static URL downURL = Data.class.getResource("static/down.png");
    public static ImageIcon down = new ImageIcon(downURL);
    public static URL leftURL = Data.class.getResource("static/left.png");
    public static ImageIcon left = new ImageIcon(leftURL);
    public static URL rightURL = Data.class.getResource("static/right.png");
    public static ImageIcon right = new ImageIcon(rightURL);
    public static URL foodURL = Data.class.getResource("static/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);
    public static URL bodyURL = Data.class.getResource("static/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);

}

package 寒假训练.狂神.GUI.Snake;

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

public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setBounds(10,10,960,800);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //绘制游戏界面
        frame.add(new GamePanel());

        frame.setVisible(true);
    }
}
package 寒假训练.狂神.GUI.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;

//游戏的面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {

    //定义蛇的数据结构
    int length;//蛇的长度
    int[] snakeX = new int[600];//蛇的X坐标
    int[] snakeY = new int[500];//蛇的Y坐标
    String fx ;//小蛇的方向

    //食物的坐标
    int foodX;
    int foodY;
    Random random = new Random();

    int score;//成绩

    //游戏当前的这状态,开始,结束
    boolean isStart = false;//默认是不开始

    boolean isFail = false;//游戏失败

    //定时器
    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] = 128; snakeY[0] = 80;
        snakeX[1] = 96; snakeY[1] = 80;
        snakeX[2] = 64; snakeY[2] = 80;

        fx = "R";//小蛇的初始方向

        // 把食物随机分布在界面上
        foodX = 32 + 32*random.nextInt(28);
        foodY = 64 + 32*random.nextInt(21);
         score = 0;
    }


    //绘制面板,游戏中的所有东西,都用这个笔来画
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        //绘制静态面板
        this.setBackground(Color.white);
        Data.header.paintIcon(this,g,50,7);//头部广告栏
        g.fillRect(32,64,896,672);//蛇的移动界面

        //画食物
        Data.food.paintIcon(this,g,foodX,foodY);

        //画积分
        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度:"+length,800,30);
        g.drawString("分数:"+score,800,50);

        //把小蛇放上去
        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,400);
        }
        if (isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("游戏失败,按下空格重新开始游戏!!!",280,400);
        }
    }

    //键盘监听器
    @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++;
                score += 10;//分数加10
                //再次随机生成食物
                foodX = 32 + 32*random.nextInt(28);
                foodY = 64 + 32*random.nextInt(21);
            }
            for (int i = length-1;i > 0;i--){
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }

            if (fx.equals("R")){
                snakeX[0]+=32;
                if (snakeX[0]>896){ snakeX[0] = 32; }
            } else if (fx.equals("L")) {
                snakeX[0] -= 32;
                if (snakeX[0] < 32) { snakeX[0] = 896; }
            } else if (fx.equals("U")){
                snakeY[0]-=32;
                if (snakeY[0] < 64){ snakeY[0] = 704; }
            }else if (fx.equals("D")){
                snakeY[0]+=32;
                if (snakeY[0] > 704){ snakeY[0] = 64; }
            }

            //失败判断
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i]&&snakeY[0] == snakeY[i]){
                    isFail = true;
                }
            }
            repaint();
        }
        timer.start();
    }

    @Override
    public void keyTyped(KeyEvent e) { }
    @Override
    public void keyReleased(KeyEvent e) { }
}

相关