JavaGUI编程个人笔记

GUI编程(了解)

组件

  • 窗口
  • 弹窗
  • 面板
  • 文本框
  • 列表框
  • 按钮
  • 图片
  • 监听事件
  • 鼠标事件
  • 键盘事件
  • 破解工具

简介

Gui开发核心技术:Swing AWT

  • 界面不美观
  • 需要jre环境
  • 但还要学习

AWT

Awt介绍

  1. 包含了很多类和接口,GUI:图形用户界面
  2. 元素:窗口,按钮,文本框
  3. java.awt

组件和容器

public static void main(String[] args) {
    // Frame
    Frame frame = new Frame("Java图形界面窗口");
    // 设置可见性
    frame.setVisible(true);
    // 设置窗口大小
    frame.setSize(400, 400);
    // 设置背景颜色
    Color color = new Color(49, 6, 6);
    frame.setBackground(Color.yellow);  // 也可以这样写
    // 弹出的初始位置
    frame.setLocation(500, 300);
    // 设置不可改变大小
    frame.setResizable(false);

}

目前还不能关闭窗口

封装到一个类中

package com.day01.lesson01;

import java.awt.*;

public class TestFrame2 {
    public static void main(String[] args) {
        // 展示多个窗口
        MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.green);
        MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.cyan);
        MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.black);
        MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.yellow);
    }
}

class MyFrame extends Frame {
    static int id = 0;  // 可能存在多个窗口,需要一个计数器

    public MyFrame(int x, int y, int width, int height, Color color) {
        super("MyFrame" + (++id));
        setVisible(true);
        setBackground(color);
        // setSize(width, height);
        // setLocation(x, y);
        setBounds(x, y, width, height);  // 等价于上面两行
    }
}

面板Panel

解决了关闭时间

package com.day01.lesson01;

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

// Panel 可以看成是一个空间,但是不能单独存在
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(255, 255, 255, 255));

        // panel设置坐标        相对于frame
        panel.setBounds(50, 50, 400, 400);
        panel.setBackground(new Color(124, 188, 231));

        // 添加panel到Frame
        frame.add(panel);

        frame.setVisible(true);
        // 监听事件,关停窗口关闭时间 System.exit(0)
        frame.addWindowListener(new WindowAdapter() {
            // 窗口点击关闭的时候要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                // 结束程序
                System.exit(0);
            }
        });

    }
}

布局管理器

  • 流体布局

    • package com.day01.lesson01;
      
      import java.awt.*;
      import java.awt.event.WindowAdapter;
      import java.awt.event.WindowEvent;
      
      public class TestFlowLayout {
          public static void main(String[] args) {
              Frame frame = new Frame();
      
              // 组件:按钮
              Button button1 = new Button("btn1");
              Button button2 = new Button("btn2");
              Button button3 = new Button("btn3");
              // 设置为流式布局
              frame.setLayout(new FlowLayout(FlowLayout.LEFT));
              frame.setSize(800, 500);
              frame.setVisible(true);
      
              // 添加按钮
              frame.add(button1);
              frame.add(button2);
              frame.add(button3);
              // 监听事件,关停窗口关闭时间 System.exit(0)
              frame.addWindowListener(new WindowAdapter() {
                  // 窗口点击关闭的时候要做的事情
                  @Override
                  public void windowClosing(WindowEvent e) {
                      // 结束程序
                      System.exit(0);
                  }
              });
      
              Label label = new Label();
          }
      }
      
  • 东西南北中

    • package com.day01.lesson01;
      
      import java.awt.*;
      
      public class TestBorderLayout {
          public static void main(String[] args) {
              Frame frame = new Frame();
      
              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.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.setSize(800, 500);
              frame.setVisible(true);
          }
      }
      
  • 表格布局

    • package com.day01.lesson01;
      
      import java.awt.*;
      
      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.add(btn1);
              frame.add(btn2);
              frame.add(btn3);
              frame.add(btn4);
              frame.add(btn5);
              frame.add(btn6);
      
              frame.pack();  // Java函数
              frame.setSize(800, 500);
              frame.setVisible(true);
          }
      }
      

总结:

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

事件监听

package com.day01.lesson02;

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 TestActionEvent {
    public static void main(String[] args) {
        // 按下按钮,触发一些事件
        Frame frame = new Frame();
        Button button = new Button("Button");
        // 因为addActionListener需要一个ActionListener,所以我们需要构造一个ActionListener
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);
        frame.add(button, BorderLayout.CENTER);
        frame.pack();  // 根据布局确定最佳大小
        frame.setBounds(400, 400,800,500);
        windowClose(frame);
        frame.setVisible(true);

    }

    // 关闭窗体事件
    private static void windowClose(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("AA");
    }
}

多个按钮共享一个事件

package com.day01.lesson02;

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 TestActionTwo {
    public static void main(String[] args) {
        // 两个按钮实现同一个监听
        // 开始  停止
        Frame frame = new Frame("开始-停止");
        Button button1 = new Button("开始");
        Button button2 = new Button("停止");
        // 可以显示的定义触发会返回的命令,如果不显示定义,那就走默认值
        // 可以多个按钮只写一个监听类
        button2.setActionCommand("button2-stop");
        MyMonitor myMonitor = new MyMonitor();
        button1.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);
        frame.add(button1, BorderLayout.NORTH);
        frame.add(button2, BorderLayout.SOUTH);
        frame.pack();
        windowClose(frame);
        frame.setVisible(true);
    }

    private static void windowClose(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyMonitor implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮clicked:msg" + e.getActionCommand());
    }
}

输入框监听

package com.day01.lesson02;

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 TestText01 {
    public static void main(String[] args) {
        MyFrame myFrame = new MyFrame();
        windowClose(myFrame);
    }

    private static void windowClose(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyFrame extends Frame {
    public MyFrame() {
        TextField textField = new TextField();
        add(textField);
        // 监听这个文本框输入的文字
        MyActionListener2 myActionListener2 = new MyActionListener2();
        // 按下enter就会触发这个输入框事件
        textField.addActionListener(myActionListener2);
        pack();
        // 设置替换编码
        textField.setEchoChar('*');
        setVisible(true);
    }
}

class MyActionListener2 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field = (TextField) e.getSource();  // 获得一些资源
        String text1 = field.getText();  // 获得输入框中的文本
        System.out.println(text1);
        field.setText("");
    }
}

简易计算器

package com.day01.lesson02;

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

// 简易计算器
public class TestCalc {
    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("=");
        button.addActionListener(new MyCalculatorListener(this));
        // 一个标签
        Label label = new Label("+");
        // 布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }

}

// 监听器类
class MyCalculatorListener implements ActionListener {
    // 获取计算器这个对象,在一个类中组合另外一个类
    Calculator calculator = null;

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

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

// 简易计算器
public class TestCalc {
    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("=");
        button.addActionListener(new MyCalculatorListener());
        // 一个标签
        Label label = new Label("+");
        // 布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }
    // 监听器类
    private class MyCalculatorListener 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("");
        }
    }

}

画笔paint

package com.day01.lesson03;

import java.awt.*;

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

class MyPaint extends Frame {

    public void loadFrame() {
        setBounds(200, 200, 800, 500);
        setVisible(true);
    }

    // 画笔
    @Override
    public void paint(Graphics g) {
        // 画笔,需要颜色,可以绘画
        g.setColor(Color.cyan);
        // g.drawOval(100, 100, 100,100);
        g.fillOval(100,100,100,100);  // 实心圆
        g.setColor(Color.BLUE);
        g.fillRect(150,200,200,200);
    }
}

鼠标监听

实现鼠标画画

package com.day01.lesson03;

import com.sun.corba.se.impl.orbutil.graph.Graph;

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

// 鼠标监听事件
public class TestMouseListener {
    public static void main(String[] args) {
        MyFrame myFrame = new MyFrame("Paint");
    }
}

class MyFrame extends Frame {
    // 绘画需要画笔,需要监听鼠标当前的位置,需要几个来存储这个点
    ArrayList points;

    public MyFrame(String title) throws HeadlessException {
        super(title);
        setBounds(400, 400, 800, 500);

        // 存鼠标点击的点
        points = new ArrayList<>();
        setVisible(true);        // 鼠标监听事件,正对这个窗口
        this.addMouseListener(new MyMouseListener());

    }

    @Override
    public void paint(Graphics g) {
        // 画画,监听鼠标事件

        Iterator iterator = points.iterator();
        while (iterator.hasNext()) {
            Point point = (Point) iterator.next();
            g.setColor(Color.cyan);
            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();
        }
    }
}

窗口监听

package com.day01.lesson03;

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

public class TestWindow {
    public static void main(String[] args) {
        new WindowFrame();
    }
}

class WindowFrame extends Frame {
    public WindowFrame() {
        setBackground(Color.cyan);
        setBounds(100, 100, 800, 500);
        setVisible(true);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                setVisible(false);  // 隐藏窗口,通过按钮,隐藏当前窗口
                System.exit(0);  // 正常退出
            }
        });
    }
}

键盘监听

package com.day01.lesson03;

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

public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}

class KeyFrame extends Frame {
    public KeyFrame() {
        setBounds(1, 2, 300, 400);
        setVisible(true);
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                // 获得按下的哪个键
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
                if (keyCode==KeyEvent.VK_UP) {
                    System.out.println("按下了👆剑");
                }
                // 根据不同的操作,产生不同的结果
            }
        });
    }
}

Swing

窗口、面板

package com.day02.lesson04;

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

public class JFrameDemo {
    //init();初始化
    public void init() {
        // JFrame 是一个顶级窗口
        JFrame jf = new JFrame("这是一个JFrame窗口");
        jf.setVisible(true);
        jf.setBackground(Color.DARK_GRAY);
        jf.setBounds(400, 400, 800, 500);
        // 设置文字JLabel
        JLabel jl = new JLabel("欢迎来到英雄联盟");
        jf.add(jl);

        // 关闭窗口事件
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        // 建立一个窗口
        new JFrameDemo().init();
    }
}
package com.day02.lesson04;

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

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

class MyJFrame02 extends JFrame {
    public void init() {
        // 获得一个容器
        Container container = this.getContentPane();
        container.setBackground(Color.MAGENTA);
        this.setVisible(true);
        this.setBounds(400, 400, 800, 500);
        // 设置文字JLabel
        JLabel jl = new JLabel("欢迎来到英雄联盟");
        this.add(jl);
        jl.setHorizontalAlignment(SwingConstants.CENTER);
    }
}

弹窗

package com.day02.lesson04;

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

// 主窗口
public class DialogDemo extends JFrame {
    public DialogDemo() {
        this.setVisible(true);
        this.setSize(800, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // JFrame 容器
        Container container = this.getContentPane();
        // 绝对布局
        container.setLayout(null);
        // 按钮
        JButton button = new JButton("弹出对话框");  // 创建
        button.setBounds(30, 30, 200, 50);
        // 点击这个按钮的时候,弹出一个弹窗
        // 监听事件
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 弹窗
                new MyDialogDemo();
            }
        });
        container.add(button);
    }

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

// 弹窗的窗口
class MyDialogDemo extends JDialog {
    public MyDialogDemo() {
        this.setVisible(true);
        this.setBounds(100, 100, 500, 500);
        Container container = this.getContentPane();
        // 默认自带关闭事件
        container.setLayout(null);
        JLabel label = new JLabel("Siu~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        label.setBounds(40,40,40,40);
        container.add(label);
    }
}

标签

new JLael();

package com.day02.lesson04;

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

public class ImageIconDemo extends JFrame {
    public ImageIconDemo() {
        // 获取图片地址
        JLabel label = new JLabel("Image Icon");
        URL url = ImageIconDemo.class.getResource("ARg.png");
        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(400, 200, 800, 500);
        JPanel jPanel1 = new JPanel();
        JPanel jPanel2 = new JPanel();
        jPanel1.setBackground(new Color(116, 172, 223));
        jPanel2.setBackground(new Color(116, 172, 223));
        jPanel2.setBounds(0, 166 * 2, 800, 166);
        container.add(jPanel1);
        container.add(jPanel2);


    }

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

面板

JPanel

package com.day02.lesson05;

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

public class JPanelDemo extends JFrame {
    public JPanelDemo() {
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(2, 1, 10, 10));  // 后面的参数是间距
        JPanel panel1 = new JPanel(new GridLayout(1,3));
        JPanel panel2 = new JPanel(new GridLayout(1,2));
        JPanel panel3 = new JPanel(new GridLayout(2,1));
        JPanel panel4 = new JPanel(new GridLayout(3,2));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("2"));
        panel1.add(new JButton("3"));
        panel2.add(new JButton("2"));
        panel2.add(new JButton("2"));
        panel3.add(new JButton("2"));
        panel3.add(new JButton("2"));
        panel4.add(new JButton("2"));
        panel4.add(new JButton("2"));
        panel4.add(new JButton("2"));
        panel4.add(new JButton("2"));
        panel4.add(new JButton("2"));
        panel4.add(new JButton("2"));
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setBounds(400, 200, 800, 500);
        container.add(panel1);
        container.add(panel2);
        container.add(panel3);
        container.add(panel4);
    }

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

JScroll

package com.day02.lesson05;


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

public class JScrollDemo extends JFrame {
    public JScrollDemo() {

        Container container = this.getContentPane();
        // 文本域
        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("Siu~~~~~~~~~~~~");
        // Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);
        this.setBounds(400, 200, 800, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

按钮

  • 单选按钮

    • package com.day02.lesson05;
      
      import javax.swing.*;
      import java.awt.*;
      import java.net.URL;
      
      public class JButtonDemo01  extends JFrame {
          public JButtonDemo01() {
              Container container = this.getContentPane();
              // 将一个图片变为图标
              URL resource = JButtonDemo01.class.getResource("ARg.png");
              Icon icon = new ImageIcon(resource);
              // 把这个图标放在按钮上
              JButton button = new JButton();
              button.setIcon(icon);
              button.setToolTipText("siu~");
              container.add(button);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setBounds(400,200,800,500);
          }
      
          public static void main(String[] args) {
              new JButtonDemo01();
          }
      }
      
    • package com.day02.lesson05;
      
      import javax.swing.*;
      import java.awt.*;
      import java.net.URL;
      
      public class JButtonDemo02 extends JFrame {
          public JButtonDemo02() {
              Container container = this.getContentPane();
              URL resource = JButtonDemo02.class.getResource("ARg.png");
              Icon icon = new ImageIcon(resource);
              // 单选框
              JRadioButton radioButton1 = new JRadioButton("Siu~01");
              JRadioButton radioButton2 = new JRadioButton("Siu~02");
              JRadioButton radioButton3 = new JRadioButton("Siu~03");
              // 单选框只能选择一个,分组,一个组中只能选择一个
              ButtonGroup group = new ButtonGroup();
              group.add(radioButton1);
              group.add(radioButton2);
              group.add(radioButton3);
              container.add(radioButton1, BorderLayout.CENTER);
              container.add(radioButton2, BorderLayout.NORTH);
              container.add(radioButton3, BorderLayout.SOUTH);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setBounds(400, 200, 800, 500);
          }
      
          public static void main(String[] args) {
              new JButtonDemo02();
          }
      }
      
  • 复选按钮

    • package com.day02.lesson05;
      
      import javax.swing.*;
      import java.awt.*;
      import java.net.URL;
      
      public class JButtonDemo03 extends JFrame{
          public JButtonDemo03() {
              Container container = this.getContentPane();
              URL resource = JButtonDemo02.class.getResource("ARg.png");
              Icon icon = new ImageIcon(resource);
              // 多选框
              JCheckBox checkBox1 = new JCheckBox("CheckBox1");
              JCheckBox checkBox2 = new JCheckBox("CheckBox2");
              JCheckBox checkBox3 = new JCheckBox("CheckBox3");
              container.add(checkBox1,BorderLayout.NORTH);
              container.add(checkBox2,BorderLayout.WEST);
              container.add(checkBox3,BorderLayout.SOUTH);
      
      
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setBounds(400, 200, 800, 500);
          }
      
          public static void main(String[] args) {
              new JButtonDemo03();
          }
      }
      

列表

  • 下拉框

    • package com.day03.lesson06;
      
      import javax.swing.*;
      import java.awt.*;
      
      public class TestComboboxDemo01 extends JFrame {
          public TestComboboxDemo01() {
              Container container = this.getContentPane();
              JComboBox status = new JComboBox();
              status.addItem(null);
              status.addItem("正在热映");
              status.addItem("已下架");
              status.addItem("即将上架");
              this.setBounds(400, 230, 800, 500);
              container.add(status);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new TestComboboxDemo01();
          }
      }
      
  • 列表框

    • package com.day03.lesson06;
      
      import javax.swing.*;
      import java.awt.*;
      import java.util.Vector;
      
      public class TestComboboxDemo02 extends JFrame {
          public TestComboboxDemo02() {
              Container container = this.getContentPane();
      
              // 生成列表内容
      //        String[] contents = {"1", "2", "3"};
              Vector contents = new Vector();
              // 列表中需要放入内容
              JList list = new JList(contents);
              contents.add("张三");
              contents.add("李四");
              contents.add("王五");
      
      
              this.setBounds(400, 230, 800, 500);
              container.add(list);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new TestComboboxDemo02();
          }
      }
      

文本框

  • 文本框

    • package com.day03.lesson06;
      
      import javax.swing.*;
      import java.awt.*;
      import java.util.Vector;
      
      public class TestTextDemo01 extends JFrame {
          public TestTextDemo01() {
              Container container = this.getContentPane();
              JTextField textField1 = new JTextField("Hello");
              JTextField textField2 = new JTextField("World!", 20);
              container.add(textField1, BorderLayout.NORTH);
              container.add(textField2, BorderLayout.SOUTH);
      
              this.setBounds(400, 230, 800, 500);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new TestTextDemo01();
          }
      }
      
  • 密码框

    • package com.day03.lesson06;
      
      import javax.swing.*;
      import java.awt.*;
      
      public class TestTextDemo02 extends JFrame {
          public TestTextDemo02() {
              Container container = this.getContentPane();
              JPasswordField passwordField = new JPasswordField();
              passwordField.setEchoChar('*');
              container.add(passwordField);
              this.setBounds(400, 230, 800, 500);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new TestTextDemo02();
          }
      }
      
  • 文本域

    • package com.day02.lesson05;
      
      
      import javax.swing.*;
      import java.awt.*;
      
      public class JScrollDemo extends JFrame {
          public JScrollDemo() {
      
              Container container = this.getContentPane();
              // 文本域
              JTextArea textArea = new JTextArea(20,50);
              textArea.setText("Siu~~~~~~~~~~~~");
              // Scroll面板
              JScrollPane scrollPane = new JScrollPane(textArea);
              container.add(scrollPane);
              this.setBounds(400, 200, 800, 500);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new JScrollDemo();
          }
      }
      

贪吃蛇

帧,如果时间片足够小,就是动画,一秒三十帧、六十帧,连起来是动画,拆开是静态的图片

键盘监听

定时器Timer


StartGame.java

package com.day03.Snake;

import javax.swing.*;

// 游戏主启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setBounds(500, 200, 900, 720);

        // 正常的游戏画面都在面板上
        GamePanel gamePanel = new GamePanel();
        frame.add(gamePanel);
        frame.setVisible(true);
    }
}

Data.java

package com.day03.Snake;

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

// 数据中心
public class Data {
    // 相对路径
    // 绝对路径
    public static URL headerURL = Data.class.getResource("statics/Score.jpg");
    public static ImageIcon header = new ImageIcon(headerURL);

    public static URL upURL = Data.class.getResource("statics/Up.png");
    public static URL downURL = Data.class.getResource("statics/Down.png");
    public static URL leftURL = Data.class.getResource("statics/Left.png");
    public static URL rightURL = Data.class.getResource("statics/Right.png");

    public static ImageIcon up = new ImageIcon(upURL);
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);

    public static URL bodyURL = Data.class.getResource("statics/GreenSquare.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
    public static URL foodURL = Data.class.getResource("statics/BlueOval.png");
    public static ImageIcon food = new ImageIcon(foodURL);


}

Gamepanel.java

package com.day03.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;  // snake的长度
    int[] snakeX = new int[600];  // 蛇的X坐标
    int[] snakeY = new int[500];  // 蛇的Y坐标

    String direction;  // 初始方向

    boolean status = false;  // 游戏当前状态,默认false
    boolean isFail = false;  // 游戏是否失败

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

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

    public GamePanel() {
        init();
        // 获得焦点和键盘事件
        this.setFocusable(true);  // 获得焦点事件
        this.addKeyListener(this);  // 获得键盘事件
        timer.start();  // 游戏开始,定时器启动
        // 随机分布食物
        foodX = 25 + 25 * random.nextInt(34);
        foodY = 75 + 25 * random.nextInt(24);
        score = 0;
    }

    // 初始化方法
    public void init() {
        length = 3;
        snakeX[0] = 100;
        snakeY[0] = 100;  // 脑袋的坐标
        snakeX[1] = 75;
        snakeY[1] = 100;  // 第一个身体坐标
        snakeX[2] = 50;
        snakeY[2] = 100;  // 第二个身体坐标
        direction = "R";  // 初始方向向右
    }

    // 绘制面板,游戏中的所有东西,都使用这个画笔画
    @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.BLACK);
        g.setFont(new Font("微软雅黑", Font.BOLD, 15));
        g.drawString("长度:" + length, 750, 35);
        g.drawString("分数:" + (length - 3) * 10, 750, 50);
        // 把食物画上去
        Data.food.paintIcon(this, g, foodX, foodY);
        // 把snake画上去
        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 (!status) {
            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("Game Over!", 300, 300);
        }
    }

    // 键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();  // 获得键盘code
        if (keyCode == KeyEvent.VK_SPACE) {  // 如果按下的是空格
            if (isFail) {
                // 重新开始
                isFail = false;
                init();
            } else {
                status = !status;
                repaint();
            }
        }
        // 小蛇移动
        if (keyCode == KeyEvent.VK_UP) {
            direction = "U";

        } else if (keyCode == KeyEvent.VK_DOWN) {
            direction = "D";

        } else if (keyCode == KeyEvent.VK_LEFT) {
            direction = "L";

        } else if (keyCode == KeyEvent.VK_RIGHT) {
            direction = "R";

        }
    }

    // 事件监听,需要通过固定事件来判断
    @Override
    public void actionPerformed(ActionEvent e) {
        if (status && !isFail) {  // 如果游戏是开始状态,就让蛇动起来
            // 吃食物
            if (snakeX[0] == foodX && snakeY[0] == foodY) {
                length++;
                // 再次生成食物
                // 随机分布食物
                foodX = 25 + 25 * random.nextInt(34);
                foodY = 75 + 25 * random.nextInt(24);
            }
            // 移动
            for (int i = length - 1; i > 0; i--) {
                snakeX[i] = snakeX[i - 1];  // 向前移动一节
                snakeY[i] = snakeY[i - 1];
            }
            // 走向
            if (direction.equals("R")) {
                snakeX[0] = snakeX[0] + 25;
                // 边界判断
                if (snakeX[0] > 850) {
                    snakeX[0] = 25;
                }
            } else if (direction.equals("L")) {
                snakeX[0] = snakeX[0] - 25;
                if (snakeX[0] < 25) {
                    snakeX[0] = 850;
                }
            } else if (direction.equals("U")) {
                snakeY[0] = snakeY[0] - 25;
                if (snakeY[0] < 75) {
                    snakeY[0] = 650;
                }
            } else if (direction.equals("D")) {
                snakeY[0] = snakeY[0] + 25;
                if (snakeY[0] > 650) {
                    snakeY[0] = 75;
                }
            }
            // 失败判断
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                    isFail = true;
                    break;
                }
            }
            repaint();
        }
        timer.start();  // 开启定时器
    }
    @Override
    public void keyTyped(KeyEvent e) {
    }
    @Override
    public void keyReleased(KeyEvent e) {
    }
}
posted @   还是啥都不会  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示