GUI编程之贪吃蛇

一、GUI编程

已经快淘汰了

怎么学?

  • 这是什么?
  • 它怎么玩?
  • 该如何在平时运用?

不是java强项,但可以做。

组件

  • 窗口
  • 弹窗
  • 面板
  • 文本框
  • 列表框
  • 按钮
  • 图片
  • 监听事件(web会有)
  • 鼠标
  • 键盘事件

1、简介

Gui的核心技术: Swing AWT

1.界面不美观

2.需要jre环境

为什么要学习?

  1. 可以写出自己心中想要的一些小工具
  2. 工作时候,也可能维护到swing界面,但概率极小。
  3. 了解MVC架构,了解监听!

2、AWT(Swing前身,讲底层的实现)

2.1 AWT介绍

  1. 包含了很多类和接口!GUI:图像用户界面。 Eeclipse:java环境写的
  2. 元素:窗口、按钮、文本框
  3. java.awt包里

2.2、组件和容器

1、Frame

  1. package com.shuai.lesson1;
  2. import java.awt.*;
  3. //GUI的第一个界面
  4. public class TestFrame {
  5. public static void main(String[] args) {
  6. //Frame,JDK 看源码;
  7. Frame frame = new Frame("我的第一个java图形界面窗口");
  8. //设置可见性 w h 没有
  9. frame.setVisible(true);
  10. //设置窗口大小
  11. frame.setSize(400, 400);
  12. //背景颜色 Color
  13. Color color = new Color(155, 89, 104);
  14. frame.setBackground(color);
  15. //弹出的初始位置
  16. frame.setLocation(200, 200);
  17. //设置大小固定
  18. frame.setResizable(false);
  19. }
  20. }

问题:窗口无法关闭—》java停止运行

尝试回顾封装:

  1. package com.shuai.lesson1;
  2. import java.awt.*;
  3. public class TestFrame2 {
  4. public static void main(String[] args) {
  5. MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.blue);
  6. MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.yellow);
  7. MyFrame myFrame3 = new MyFrame(500, 100, 200, 200, Color.RED);
  8. MyFrame myFrame4 = new MyFrame(700, 100, 200, 200, Color.BLACK);
  9. }
  10. }
  11. class MyFrame extends Frame{
  12. //除了Frame方法以外,还有自己的方法
  13. static int id = 0;//可能存在多个窗口,我们需要一个计数器
  14. //构造器封装一下
  15. public MyFrame(int x,int y, int w,int h,Color color){
  16. super("MyFrame+"+(++id));
  17. setBackground(color);
  18. setVisible(true);
  19. //相当于初始位置x,y和窗口大小w h
  20. setBounds(x,y,w,h);
  21. setResizable(false);
  22. }
  23. }`

2、面板panel

解决了无法关闭问题,即调用addWindowsListener方法的子方法,并重写其中的WindowsClosing方法,来调用程序关闭的.exit(0)方法

  1. package com.shuai.lesson1;
  2. import java.awt.*;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. import java.awt.event.WindowListener;
  6. //Panel 可以看成一个空间,但是不能单独存在,得放在Frame上
  7. public class TsetPanel {
  8. public static void main(String[] args) {
  9. //窗口
  10. Frame frame = new Frame();
  11. //布局的概念
  12. //面板
  13. Panel panel = new Panel();
  14. /*设置布局 不设置会默认置顶
  15. 未设置Layout时,java默认为flowLayout布局的,
  16. 设置为null即为清空布局管理器,之后添加组件,常常是设置组件左上角坐标相
  17. 对于容器左上角(0,0)的x,y值来确定组件的位置,即使更改容器大小也不会
  18. 改变位置。这种方式常常用于窗体大小固定的容器里。*/
  19. frame.setLayout(null);
  20. //坐标
  21. frame.setBounds(300,300,500,500);
  22. frame.setBackground(new Color(59, 164, 125));
  23. //panel 设置坐标,相对于Frame的坐标
  24. panel.setBounds(50,50,200,200);
  25. panel.setBackground(new Color(90, 46, 30));
  26. //frame.add(panel)frame添加面板
  27. frame.add(panel);//Panel经过三层继承,最终继承了Component
  28. frame.setVisible(true);
  29. //监听时间,监听窗口关闭事件 System.exit(0)
  30. //适配器模式: new 重写的太多了 new其子类 本来new WindowsListener的,但是要重写的实在太多了
  31. frame.addWindowListener(new WindowAdapter() {
  32. //窗口点击关闭的时候需要做的事情
  33. @Override
  34. public void windowClosing(WindowEvent e) {
  35. //结束程序
  36. System.exit(0);
  37. }
  38. });
  39. }
  40. }

2.3、布局管理器

流式布局 从左到右
  1. package com.shuai.lesson1;
  2. import java.awt.*;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. public class TsetFlowLayout {
  6. public static void main(String[] args) {
  7. Frame frame = new Frame();
  8. //组件-按钮
  9. Button button1 = new Button("button1");
  10. Button button2 = new Button("button2");
  11. Button button3 = new Button("button3");
  12. //设置为流式布局
  13. //frame.setLayout(new FlowLayout());默认是中
  14. //frame.setLayout(new FlowLayout(FlowLayout.LEFT));
  15. frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
  16. frame.setSize(200,200);
  17. frame.setVisible(true);
  18. frame.add(button1);
  19. frame.add(button2);
  20. frame.add(button3);
  21. frame.addWindowListener(new WindowAdapter() {
  22. //窗口点击关闭的时候需要做的事情
  23. @Override
  24. public void windowClosing(WindowEvent e) {
  25. //结束程序
  26. System.exit(0);
  27. }
  28. });
  29. }
  30. }
东西南北中
  1. package com.shuai.lesson1;
  2. import java.awt.*;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. public class TestBorderLayout {
  6. public static void main(String[] args) {
  7. Frame frame = new Frame("TestBorderLayout");
  8. Button east = new Button("East");
  9. Button west = new Button("West");
  10. Button south = new Button("South");
  11. Button north = new Button("North");
  12. Button center = new Button("Center");
  13. frame.add(east,BorderLayout.EAST);
  14. frame.add(west ,BorderLayout.WEST);
  15. frame.add(south ,BorderLayout.SOUTH);
  16. frame.add(north ,BorderLayout.NORTH);
  17. frame.add(center,BorderLayout.CENTER);
  18. frame.setSize(300,300);
  19. frame.setVisible(true);
  20. frame.addWindowListener(new WindowAdapter() {
  21. @Override
  22. public void windowClosing(WindowEvent e) {
  23. System.exit(0);
  24. }
  25. });
  26. }
  27. }
表格布局三行两列这种Grid
  1. package com.shuai.lesson1;
  2. import java.awt.*;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. public class TestGridLayout {
  6. public static void main(String[] args) {
  7. Frame frame = new Frame("TsetGridLayout");
  8. Button button1 = new Button("button1");
  9. Button button2 = new Button("button2");
  10. Button button3 = new Button("button3");
  11. Button button4 = new Button("button4");
  12. Button button5 = new Button("button5");
  13. Button button6 = new Button("button6");
  14. frame.setLayout(new GridLayout(3,2));
  15. frame.add(button1);
  16. frame.add(button2);
  17. frame.add(button3);
  18. frame.add(button4);
  19. frame.add(button5);
  20. frame.add(button6);
  21. frame.pack();//让布局变得好看
  22. frame.setVisible(true);
  23. frame.addWindowListener(new WindowAdapter() {
  24. @Override
  25. public void windowClosing(WindowEvent e) {
  26. System.exit(0);
  27. }
  28. });
  29. }
  30. }

<img src="image-20210225151302140.png" alt="image-20210225151302140" style="zoom: 50%;" />

练习 做出如下界面

<img src="image-20210225155103185.png" alt="image-20210225155103185" style="zoom:50%;" />

  • 分析过程

image-20210225155417332

  • 代码实现
  1. package com.shuai.lesson1;
  2. import jdk.nashorn.api.tree.NewTree;
  3. import java.awt.*;
  4. import java.io.FileOutputStream;
  5. public class TestLayoutLianxi {
  6. public static void main(String[] args) {
  7. Frame frame = new Frame("TestLayoutLianxi");
  8. frame.setSize(400,300);
  9. frame.setLocation(300,300);
  10. frame.setBackground(Color.BLUE);
  11. frame.setVisible(true);
  12. frame.setLayout(new GridLayout(2,1));
  13. Panel panel1 = new Panel(new BorderLayout());
  14. Panel panel2 = new Panel(new GridLayout(2,1));
  15. Panel panel3 = new Panel(new BorderLayout());
  16. Panel panel4 = new Panel(new GridLayout(2,2));
  17. Button button1 = new Button("BUTTON1");
  18. Button button2 = new Button("BUTTON2");
  19. Button button3 = new Button("BUTTON3");
  20. Button button4 = new Button("BUTTON4");
  21. Button button5 = new Button("BUTTON5");
  22. Button button6 = new Button("BUTTON6");
  23. Button button7 = new Button("BUTTON7");
  24. Button button8 = new Button("BUTTON8");
  25. Button button9 = new Button("BUTTON9");
  26. Button button10 = new Button("BUTTON10");
  27. panel1.add(button1,BorderLayout.EAST);
  28. panel1.add(button2,BorderLayout.WEST);
  29. panel2.add(button3);
  30. panel2.add(button4);
  31. panel1.add(panel2,BorderLayout.CENTER);
  32. panel3.add(button5,BorderLayout.EAST);
  33. panel3.add(button6,BorderLayout.WEST);
  34. panel4.add(button7);
  35. panel4.add(button8);
  36. panel4.add(button9);
  37. panel4.add(button10);
  38. panel3.add(panel4,BorderLayout.CENTER);
  39. frame.add(panel1);
  40. frame.add(panel3);
  41. }
  42. }

之前的知识总结

  1. Frame是一个顶级窗口

  2. Panel无法单独显示,必须添加到某个容器中

  3. 布局管理器
    1. 流失
    2. 东西南北中
    3. 表格
  4. 标题,大小,定位,背景颜色,可见性,监听

2.4、事件监听

事件监听:当某个事件发生的时候,干什么?
  1. package com.shuai.lesson2;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.WindowAdapter;
  6. import java.awt.event.WindowEvent;
  7. public class TestActionEvent {
  8. public static void main(String[] args) {
  9. //按下按钮,触发一些事件
  10. Frame frame = new Frame();
  11. Button button1 = new Button("button1");
  12. //因为addActionListener需要ActionListener,因此我们需要构造一个ActionListener
  13. MyActionListener myActionListener = new MyActionListener();
  14. button1.addActionListener(new MyActionListener());
  15. frame.add(button1, BorderLayout.CENTER);
  16. frame.pack();
  17. frame.setVisible(true);
  18. windowsClosing(frame);
  19. }
  20. //关闭窗体的事件
  21. private static void windowsClosing(Frame frame){
  22. frame.addWindowListener(new WindowAdapter() {
  23. @Override
  24. public void windowClosing(WindowEvent e) {
  25. System.exit(0);
  26. }
  27. });
  28. }
  29. //事件监听
  30. static class MyActionListener implements ActionListener {
  31. @Override
  32. public void actionPerformed(ActionEvent e) {
  33. System.out.println("11");
  34. }
  35. }
  36. }
多个按钮共享一个事件
  1. package com.shuai.lesson2;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.io.FileOutputStream;
  6. public class TestActionEvent2 {
  7. public static void main(String[] args) {
  8. //两个按钮,实现同一个监听
  9. Frame frame = new Frame("1111");
  10. Button button1 = new Button("start");
  11. Button button2 = new Button("stop");
  12. //可以显示的定义出发会返回的命令,如果不显示定义,则会走默认值
  13. //可以多个按钮只写一个监听类
  14. button1.setActionCommand("3333");
  15. My my = new My();
  16. button1.addActionListener(my);
  17. button2.addActionListener(my);
  18. frame.add(button1, BorderLayout.WEST);
  19. frame.add(button2, BorderLayout.EAST);
  20. frame.pack();
  21. frame.setVisible(true);
  22. }
  23. static class My implements ActionListener {
  24. @Override
  25. public void actionPerformed(ActionEvent e) {
  26. //e.getActionCommand()获得按钮的信息
  27. System.out.println("按钮被点击了:msg" + e.getActionCommand());
  28. }
  29. }
  30. }

2.5、输入框事件监听TextField

输入框中输入的字,可以打印出来,并将输入的字全部删除。

  1. package com.shuai.lesson2;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. public class TestText01 {
  6. public static void main(String[] args) {
  7. //启动!只负责启动
  8. new MyFrame();
  9. }
  10. }
  11. class MyFrame extends Frame{
  12. public MyFrame(){
  13. TextField textField = new TextField();
  14. add(textField);
  15. //监听这个文本框输入的文字
  16. //按下回车键,就会触发这个输入框的事件,在下边的重写方法中重写的语句为 获得输入框的文本并打印
  17. textField.addActionListener(new My());
  18. //设置替换编码
  19. textField.setEchoChar('*');
  20. setVisible(true);
  21. pack();
  22. }
  23. }
  24. class My implements ActionListener{
  25. @Override
  26. public void actionPerformed(ActionEvent e) {
  27. TextField text = (TextField) e.getSource();//获得一些资源,返回的一个对象
  28. System.out.println(text.getText());//获得输入框的文本
  29. //每次都设置为空 即每次文本框输入完以后,都会全部删除清零
  30. text.setText("");
  31. }
  32. }

2.6、简易计算器,组合+内部类回顾复习

oop原则:组合,大于继承

初始版本
  1. package com.shuai.lesson2;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.TextEvent;
  6. public class TestCALC {
  7. public static void main(String[] args) {
  8. new Calculator();
  9. }
  10. }
  11. //计算器类
  12. class Calculator extends Frame {
  13. public Calculator() {
  14. //3个文本框
  15. TextField textField = new TextField(10);//字符数
  16. TextField textField1 = new TextField(10);//字符数
  17. TextField textField2 = new TextField(20);//字符数
  18. //1 个按钮
  19. Button button = new Button("=");
  20. button.addActionListener(new MyAL(textField,textField1,textField2));
  21. //1个标签
  22. Label label = new Label("+");
  23. setLayout(new FlowLayout());
  24. add(textField);
  25. add(label);
  26. add(textField1);
  27. add(button);
  28. add(textField2);
  29. pack();
  30. setVisible(true);
  31. }
  32. }
  33. //监听器类
  34. class MyAL implements ActionListener {
  35. //获取三个变量
  36. private TextField textField,textField1,textField2;
  37. public MyAL(TextField textField, TextField textField1, TextField textField2){
  38. this.textField = textField;
  39. this.textField1 = textField1;
  40. this.textField2 = textField2;
  41. }
  42. @Override
  43. public void actionPerformed(ActionEvent e) {
  44. //1.获得加数和被加数
  45. int n = Integer.parseInt(textField.getText());
  46. int n1 = Integer.parseInt(textField1.getText());
  47. //2.将这个值加法运算后,放到第三个框
  48. textField2.setText(""+(n+n1));
  49. //3.清除前两个框
  50. textField.setText("");
  51. textField1.setText("");
  52. }
  53. }
改进版本
  • 完全改造成面向对象
  1. package com.shuai.lesson2;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.TextEvent;
  6. public class TestCALC {
  7. public static void main(String[] args) {
  8. new Calculator().loadFrame();
  9. }
  10. }
  11. //计算器类
  12. //方法
  13. class Calculator extends Frame {
  14. //属性
  15. TextField textField;
  16. TextField textField1;
  17. TextField textField2;
  18. //方法
  19. public void loadFrame() {
  20. //3个文本框
  21. textField = new TextField(10);//字符数
  22. textField1 = new TextField(10);//字符数
  23. textField2 = new TextField(20);//字符数
  24. //1 个按钮
  25. Button button = new Button("=");
  26. button.addActionListener(new MyAL(this));
  27. //1个标签
  28. Label label = new Label("+");
  29. setLayout(new FlowLayout());
  30. add(textField);
  31. add(label);
  32. add(textField1);
  33. add(button);
  34. add(textField2);
  35. pack();
  36. setVisible(true);
  37. }
  38. }
  39. //监听器类
  40. class MyAL implements ActionListener {
  41. /* //获取三个变量
  42. private TextField textField,textField1,textField2;
  43. public MyAL(TextField textField, TextField textField1, TextField textField2){
  44. this.textField = textField;
  45. this.textField1 = textField1;
  46. this.textField2 = textField2;
  47. }
  48. @Override
  49. public void actionPerformed(ActionEvent e) {
  50. //1.获得加数和被加数
  51. int n = Integer.parseInt(textField.getText());
  52. int n1 = Integer.parseInt(textField1.getText());
  53. //2.将这个值加法运算后,放到第三个框
  54. textField2.setText(""+(n+n1));
  55. //3.清除前两个框
  56. textField.setText("");
  57. textField1.setText("");
  58. }
  59. }
  60. */
  61. //改进算法
  62. //获取计算器这个对象,在一个类中组合另外一个类
  63. Calculator calculator = null;
  64. public MyAL(Calculator calculator) {
  65. this.calculator = calculator;
  66. }
  67. @Override
  68. public void actionPerformed(ActionEvent e) {
  69. //1.获得加数和被加数
  70. //2.将这个值加法运算后,放到第三个框
  71. //3.清除前两个框
  72. int text = Integer.parseInt(calculator.textField.getText());
  73. int text1= Integer.parseInt(calculator.textField1.getText());
  74. calculator.textField2.setText(""+(text1+text));
  75. calculator.textField.setText("");
  76. calculator.textField.setText("");
  77. }
  78. }

还得把如下所示的代码组合一下,传递监听器麻烦

  1. Calculator calculator = null;
  2. public MyAL(Calculator calculator) {
  3. this.calculator = calculator;
  4. }
内部类
  • 最大的好处,就是可以畅通无阻的访问外部的属性和方法
  1. package com.shuai.lesson2;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.TextEvent;
  6. public class TestCALC {
  7. public static void main(String[] args) {
  8. new Calculator().loadFrame();
  9. }
  10. }
  11. //计算器类
  12. //方法
  13. class Calculator extends Frame {
  14. //属性
  15. TextField textField;
  16. TextField textField1;
  17. TextField textField2;
  18. //方法
  19. public void loadFrame() {
  20. //3个文本框
  21. textField = new TextField(10);//字符数
  22. textField1 = new TextField(10);//字符数
  23. textField2 = new TextField(20);//字符数
  24. //1 个按钮
  25. Button button = new Button("=");
  26. button.addActionListener(new MyAL());
  27. //1个标签
  28. Label label = new Label("+");
  29. setLayout(new FlowLayout());
  30. add(textField);
  31. add(label);
  32. add(textField1);
  33. add(button);
  34. add(textField2);
  35. pack();
  36. setVisible(true);
  37. }
  38. private class MyAL implements ActionListener {
  39. @Override
  40. public void actionPerformed(ActionEvent e) {
  41. //1.获得加数和被加数
  42. //2.将这个值加法运算后,放到第三个框
  43. //3.清除前两个框
  44. int text = Integer.parseInt(textField.getText());
  45. int text1 = Integer.parseInt(textField1.getText());
  46. textField2.setText("" + (text1 + text));
  47. textField.setText("");
  48. textField.setText("");
  49. }
  50. }

2.7、画笔

  1. package com.shuai.lesson3;
  2. import java.awt.*;
  3. public class TestPaint {
  4. public static void main(String[] args) {
  5. new MYpaint().loadFrame1();
  6. }
  7. }
  8. class MYpaint extends Frame{
  9. public void loadFrame1(){
  10. setBounds(200,200,600,400);
  11. setVisible(true);
  12. }
  13. @Override
  14. public void paint(Graphics g) {
  15. //super.paint(g);有些类的父类有一些初始化操作,不能随便干掉
  16. //画笔,需要颜色,画笔可以画画
  17. g.setColor(Color.red);
  18. g.drawOval(100,100,100,100);
  19. g.fillOval(200,200,100,100);//实心的⚪
  20. g.setColor(Color.green);
  21. g.fillRect(300,300,40,20);
  22. g.drawRect(300,350,40,20);
  23. //养成习惯 画笔画完,将他还原到最初的颜色
  24. g.setColor(Color.BLACK);
  25. }
  26. }

2.8、鼠标监听

目的:想要实现鼠标画画!

  1. package com.shuai.lesson3;
  2. import java.awt.*;
  3. import java.awt.event.MouseAdapter;
  4. import java.awt.event.MouseEvent;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. //鼠标监听事件
  8. public class TestMouseListener {
  9. public static void main(String[] args) {
  10. new MyFrame("画图");
  11. }
  12. }
  13. //自己的类
  14. class MyFrame extends Frame {
  15. //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
  16. ArrayList points;
  17. public MyFrame(String title) {
  18. super(title);
  19. setBounds(100, 100, 500, 400);
  20. //存鼠标的点
  21. points = new ArrayList<>();
  22. //鼠标监听器,针对这个窗口
  23. setVisible(true);
  24. this.addMouseListener(new MyML());
  25. }
  26. @Override
  27. public void paint(Graphics g) {
  28. //画画,监听鼠标的事件
  29. Iterator iterator = points.iterator();
  30. while (iterator.hasNext()){
  31. Point point = (Point) iterator.next();
  32. g.setColor(Color.BLUE);
  33. g.fillOval(point.x,point.y,10,10);
  34. }
  35. }
  36. //添加一个点到界面上
  37. public void addPaint(Point point){
  38. points.add(point);
  39. }
  40. //适配器模式
  41. private class MyML extends MouseAdapter {
  42. //鼠标 按下,弹起,按住不放
  43. @Override
  44. public void mouseClicked(MouseEvent e) {
  45. MyFrame myframe = (MyFrame) e.getSource();
  46. //这里我们点击的时候,就会在界面产生一个点
  47. myframe.addPaint(new Point(e.getX(),e.getY()));
  48. //每次点击鼠标都需要重新画一遍
  49. myframe.repaint();//刷新
  50. }
  51. }
  52. }

2.9、窗口监听

  1. package com.shuai.lesson3;
  2. import java.awt.*;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. public class TestWindow {
  6. public static void main(String[] args) {
  7. new WindowF();
  8. }
  9. }
  10. class WindowF extends Frame {
  11. public WindowF() {
  12. setBackground(Color.BLUE);
  13. setBounds(100, 100, 200, 200);
  14. setVisible(true);
  15. this.addWindowListener(
  16. //匿名内部类
  17. new WindowAdapter() {
  18. @Override
  19. public void windowClosing(WindowEvent e) {
  20. System.out.println("windowsClosing");
  21. System.exit(0);
  22. }
  23. @Override
  24. public void windowActivated(WindowEvent e) {
  25. WindowF source = (WindowF) e.getSource();
  26. source.setTitle("已激活");
  27. System.out.println("windowActivated");
  28. }
  29. });
  30. }
  31. /* @Override
  32. public void windowClosing(WindowEvent e) {
  33. setVisible(false);// 隐藏窗口
  34. System.exit(0);//正常退出 1是非正常退出
  35. };*/
  36. }

2.10 键盘监听

  1. package com.shuai.lesson3;
  2. import java.awt.*;
  3. import java.awt.event.KeyAdapter;
  4. import java.awt.event.KeyEvent;
  5. import java.sql.SQLOutput;
  6. //键
  7. public class TestKeyListener {
  8. public static void main(String[] args) {
  9. new KeyF();
  10. }
  11. }
  12. class KeyF extends Frame{
  13. public KeyF(){
  14. setBounds(0,0,300,400);
  15. setVisible(true);
  16. this.addKeyListener(new KeyAdapter() {
  17. //键盘按下
  18. @Override
  19. public void keyPressed(KeyEvent e) {
  20. int keyCode = e.getKeyCode();//不需要去记录这个数值,直接使用静态属性VK_xxx
  21. System.out.println(keyCode);
  22. if (keyCode == KeyEvent.VK_UP){
  23. System.out.println("你按了上键盘");
  24. //根据不同的操作,进行不同的结果
  25. }
  26. }
  27. });
  28. }
  29. }

3、Swing(做界面)

3.1、窗口、面板JFrame

  1. package com.shuai.lesson4;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. public class JFrameDemo {
  5. //init();初始化
  6. public void init(){
  7. //顶级窗口
  8. JFrame jf = new JFrame("这是一个JFrame窗口");
  9. jf.setBounds(100,100,400,300);
  10. //设置文字Label->JLabel
  11. jf.setBackground(Color.BLUE);
  12. JLabel jl = new JLabel("JJJJJ");
  13. jf.add(jl);
  14. //让文本标签居中
  15. jl.setHorizontalAlignment(SwingConstants.CENTER);
  16. //容器实例化
  17. jf.getContentPane().setBackground(Color.red);
  18. jf.setVisible(true);
  19. //关闭事件
  20. jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  21. }
  22. public static void main(String[] args) {
  23. //建立一个窗口
  24. new JFrameDemo().init();
  25. }
  26. }

3.2、弹窗

  1. package com.shuai.lesson4;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. public class DialogDemo extends JFrame {
  7. public DialogDemo() {
  8. this.setVisible(true);
  9. this.setBounds(100, 100, 400, 400);
  10. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  11. //Jframe 放东西,容器
  12. Container contentPane = this.getContentPane();
  13. //绝对布局
  14. contentPane.setLayout(null);
  15. //设置背景
  16. contentPane.setBackground(Color.BLUE);
  17. //按钮
  18. JButton jButton = new JButton("点击弹出一个对话框");
  19. jButton.setBounds(30, 30, 200, 50);
  20. //点击按钮弹出弹框
  21. jButton.addActionListener(new ActionListener() {//监听器
  22. @Override
  23. public void actionPerformed(ActionEvent e) {
  24. //弹窗
  25. new MyDialog();
  26. }
  27. });
  28. contentPane.add(jButton);
  29. }
  30. public static void main(String[] args) {
  31. new DialogDemo();
  32. }
  33. }
  34. //弹窗的窗口
  35. class MyDialog extends JDialog {
  36. public MyDialog() {
  37. this.setVisible(true);
  38. this.setBounds(100, 100, 500, 500);
  39. // this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  40. this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
  41. //JDialog退出只能是D0_ONTHING,HIDE,DISPOSE这三个中的一种
  42. //应该是默认就有关闭事件
  43. this.setTitle("这是一个弹窗");
  44. Container contentPane = this.getContentPane();
  45. contentPane.setLayout(null);
  46. contentPane.setBackground(Color.ORANGE);
  47. JLabel jjj = new JLabel("学习学习");
  48. contentPane.add(jjj);
  49. jjj.setBounds(20,20,50,50);
  50. }
  51. }

3.3、标签

label
  1. new JLabel("xxx");
图标Icon
  1. package com.shuai.lesson4;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. //图标,需要实现类,Frame继承
  5. public class IconDemo extends JFrame implements Icon {
  6. private int width;
  7. private int hight;
  8. public IconDemo(){};//无参构造
  9. //有参构造
  10. public IconDemo(int width,int hight){
  11. this.width = width;
  12. this.hight = hight;
  13. };
  14. public void init(){
  15. IconDemo iconDemo = new IconDemo(15, 15);
  16. //图标可以放在标签,也可以放在按钮上!
  17. JLabel jLabel = new JLabel("标签",iconDemo,SwingConstants.CENTER);
  18. Container contentPane = getContentPane();
  19. contentPane.add(jLabel);
  20. this.setVisible(true);
  21. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  22. }
  23. @Override
  24. public void paintIcon(Component c, Graphics g, int x, int y) {
  25. g.fillOval(x,y,width,hight);
  26. }
  27. @Override
  28. public int getIconWidth() {
  29. return this.width;
  30. }
  31. @Override
  32. public int getIconHeight() {
  33. return this.hight;
  34. }
  35. public static void main(String[] args) {
  36. new IconDemo().init();
  37. }
  38. }
图片
  1. package com.shuai.lesson4;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.net.URL;
  5. public class ImageIconDemo extends JFrame {
  6. public ImageIconDemo(){
  7. JLabel jLabel = new JLabel("图片");
  8. URL resource = ImageIconDemo.class.getResource("4.png");
  9. ImageIcon imageIcon = new ImageIcon(resource);
  10. jLabel.setIcon(imageIcon);
  11. jLabel.setHorizontalAlignment(SwingConstants.CENTER);
  12. Container contentPane = getContentPane();
  13. contentPane.add(jLabel);
  14. this.setVisible(true);
  15. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  16. setBounds(100,100,800,800);
  17. }
  18. public static void main(String[] args) {
  19. new ImageIconDemo();
  20. }
  21. }

3.4、面板

JPanel
  1. package com.shuai.lesson5;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. public class JPanelDemo extends JFrame {
  5. public JPanelDemo(){
  6. Container contentPane = this.getContentPane();
  7. contentPane.setLayout(new GridLayout(2,1,10,10));//后边两个是间距
  8. JPanel jPanel = new JPanel(new GridLayout(1, 3));
  9. JPanel jPane2 = new JPanel(new GridLayout(1, 2));
  10. JPanel jPane3 = new JPanel(new GridLayout(1, 1));
  11. jPanel.add(new JButton("aaa"));
  12. jPanel.add(new JButton("bbb"));
  13. jPanel.add(new JButton("ccc"));
  14. jPane2.add(new JButton("111"));
  15. jPane2.add(new JButton("222"));
  16. jPane3.add(new JButton("---"));
  17. setBounds(100,100,500,400);
  18. setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  19. contentPane.add(jPanel);
  20. contentPane.add(jPane2);
  21. contentPane.add(jPane3);
  22. setVisible(true);
  23. contentPane.setBackground(Color.YELLOW);
  24. }
  25. public static void main(String[] args) {
  26. new JPanelDemo();
  27. }
  28. }
JScrollPanel
  1. package com.shuai.lesson4;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. public class JScrollPanelDemo extends JFrame {
  5. public JScrollPanelDemo(){
  6. Container contentPane = this.getContentPane();
  7. //文本域
  8. JTextArea jTextArea = new JTextArea(20, 50);
  9. jTextArea.setText("学习学习");
  10. //面板 并添加到contentpane
  11. contentPane.add(new JScrollPane(jTextArea));
  12. this.setVisible(true);
  13. this.setBounds(100,100,400,300);
  14. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  15. contentPane.setBackground(Color.BLUE);
  16. }
  17. public static void main(String[] args) {
  18. new JScrollPanelDemo();
  19. }
  20. }

3.5、按钮

图片按钮
  1. package com.shuai.lesson5;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.net.URL;
  5. public class JButtonDemo01 extends JFrame {
  6. public JButtonDemo01(){
  7. Container contentPane = this.getContentPane();
  8. //图片变为图标
  9. URL resource = JButtonDemo01.class.getResource("4.png");
  10. Icon icon = new ImageIcon(resource);
  11. JButton jButton = new JButton();
  12. jButton.setIcon(icon);
  13. //悬浮框
  14. jButton.setToolTipText("这是一个图片按钮");
  15. contentPane.add(jButton);
  16. this.setVisible(true);
  17. this.setBounds(100,100,400,300);
  18. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  19. }
  20. public static void main(String[] args) {
  21. new JButtonDemo01();
  22. }
  23. }
单选按钮
  1. package com.shuai.lesson5;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.net.URL;
  5. public class JButtonDemo02 extends JFrame {
  6. public JButtonDemo02(){
  7. Container contentPane = this.getContentPane();
  8. //图片变为图标
  9. URL resource = JButtonDemo01.class.getResource("4.png");
  10. Icon icon = new ImageIcon(resource);
  11. //单选框
  12. JRadioButton jrb01 = new JRadioButton("jrb01");
  13. JRadioButton jrb02 = new JRadioButton("jrb02");
  14. JRadioButton jrb03 = new JRadioButton("jrb03");
  15. //由于单选框只能选择一个,分组
  16. ButtonGroup buttonGroup = new ButtonGroup();
  17. buttonGroup.add(jrb01);
  18. buttonGroup.add(jrb02);
  19. buttonGroup.add(jrb03);
  20. contentPane.add(jrb01,BorderLayout.CENTER);
  21. contentPane.add(jrb02,BorderLayout.NORTH);
  22. contentPane.add(jrb03,BorderLayout.SOUTH);
  23. this.setVisible(true);
  24. this.setBounds(100,100,400,300);
  25. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  26. }
  27. public static void main(String[] args) {
  28. new JButtonDemo02();
  29. }
  30. }
复选按钮
  1. package com.shuai.lesson5;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.net.URL;
  5. public class JButtonDemo03 extends JFrame {
  6. public JButtonDemo03(){
  7. Container contentPane = this.getContentPane();
  8. //图片变为图标
  9. URL resource = JButtonDemo01.class.getResource("4.png");
  10. Icon icon = new ImageIcon(resource);
  11. //多选框
  12. JCheckBox jcb1 = new JCheckBox("jcb1");
  13. JCheckBox jcb2 = new JCheckBox("jcb2");
  14. JCheckBox jcb3 = new JCheckBox("jcb3");
  15. //流式布局
  16. contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
  17. contentPane.add(jcb1);
  18. contentPane.add(jcb2);
  19. contentPane.add(jcb3);
  20. //东西南北中布局
  21. /*
  22. contentPane.add(jcb1,BorderLayout.NORTH);
  23. contentPane.add(jcb2,BorderLayout.CENTER);
  24. contentPane.add(jcb3,BorderLayout.SOUTH);
  25. */
  26. this.setVisible(true);
  27. this.setBounds(100,100,400,300);
  28. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  29. }
  30. public static void main(String[] args) {
  31. new JButtonDemo03();
  32. }
  33. }

3.6、列表

下拉框
  1. package com.shuai.lesson6;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. public class TestComboboxDemo01 extends JFrame {
  5. public TestComboboxDemo01(){
  6. Container container = this.getContentPane();
  7. JComboBox status = new JComboBox();
  8. status.addItem("未上映");
  9. status.addItem("正在热映");
  10. status.addItem("已下架");
  11. container.add(status);
  12. this.setVisible(true);
  13. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  14. this.setBounds(100,100,500,400);
  15. }
  16. public static void main(String[] args) {
  17. new TestComboboxDemo01();
  18. }
  19. }
列表框
  1. package com.shuai.lesson6;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.util.Vector;
  5. public class TestComboboxDemo02 extends JFrame {
  6. public TestComboboxDemo02(){
  7. Container container = this.getContentPane();
  8. //生成列表的内容
  9. // String[] contents = {"1","2","3"};
  10. //列表中需要的内容
  11. Vector contents = new Vector();
  12. JList jList = new JList(contents);
  13. JList jList1 = new JList(contents);
  14. contents.add("2222");
  15. contents.add("333");
  16. container.add(jList);
  17. this.setVisible(true);
  18. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  19. this.setBounds(100,100,500,400);
  20. }
  21. public static void main(String[] args) {
  22. new TestComboboxDemo02();
  23. }
  24. }

应用场景

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

3.7、文本框

文本框
  1. package com.shuai.lesson6;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. public class TestTextDemo01 extends JFrame {
  5. public TestTextDemo01(){
  6. Container container = this.getContentPane();
  7. //不布局只会出现WORLD,且位置不对
  8. this.setLayout(new FlowLayout(FlowLayout.RIGHT));
  9. JTextField jTextField1 = new JTextField("HELLO");
  10. JTextField jTextField2 = new JTextField("WORLD",20);
  11. container.add(jTextField1);
  12. container.add(jTextField2);
  13. this.setVisible(true);
  14. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  15. this.setBounds(100,100,400,300);
  16. }
  17. public static void main(String[] args) {
  18. new TestTextDemo01();
  19. }
  20. }
密码框
  1. package com.shuai.lesson6;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. public class TestTextDemo02 extends JFrame {
  5. public TestTextDemo02(){
  6. Container container = this.getContentPane();
  7. JPasswordField jPasswordField = new JPasswordField();//---
  8. jPasswordField.setEchoChar('-');
  9. container.add(jPasswordField);
  10. this.setVisible(true);
  11. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  12. this.setBounds(100,100,400,300);
  13. }
  14. public static void main(String[] args) {
  15. new TestTextDemo02();
  16. }
  17. }
文本域
  1. //文本域
  2. JTextArea jTextArea = new JTextArea(20, 50);
  3. jTextArea.setText("学习学习");
  4. //面板 并添加到contentpane
  5. contentPane.add(new JScrollPane(jTextArea))

4、贪吃蛇

启动

 1 package com.dong.sanke;
 2 
 3 import javax.swing.*;
 4 
 5 public class SnakeDemo {
 6     public static void main(String[] args) {
 7         JFrame frame = new JFrame();
 8         frame.setBounds(10,10,900,720);
 9         frame.setResizable(false);
10         frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
11 
12 
13         frame.add(new SnakePanel());
14 
15 
16         frame.setVisible(true);
17     }
18 }

主方法

  1 package com.dong.sanke;
  2 
  3 import javax.swing.*;
  4 import java.awt.*;
  5 import java.awt.event.ActionEvent;
  6 import java.awt.event.ActionListener;
  7 import java.awt.event.KeyEvent;
  8 import java.awt.event.KeyListener;
  9 import java.util.Random;
 10 
 11 public class SnakePanel extends JPanel implements KeyListener , ActionListener {
 12     int length;
 13     int[] snakeX = new int[600];
 14     int[] snakeY = new int[500];
 15     String fx ;
 16     boolean isStart ;
 17     boolean isFail;
 18     Timer timer =new Timer(100,this);
 19     Random random = new Random();
 20     int foodx;
 21     int foody;
 22     int socer;
 23     public SnakePanel() {
 24         init();
 25         this.setFocusable(true);//获得焦点事件
 26         this.addKeyListener(this);//获得键盘键盘监听事件
 27         timer.start();
 28     }
 29     //初始化
 30     public void init(){
 31         length = 3;
 32         snakeX[0]=100;snakeY[0]=100;
 33         snakeX[1]=75;snakeY[1]=100;
 34         snakeX[2]=50;snakeY[2]=100;
 35         fx = "R";
 36         isStart = false;
 37         foodx = 25+25*random.nextInt(34);
 38         foody = 75+25*random.nextInt(34);
 39         socer = 10;
 40     }
 41     //画画
 42     @Override
 43     protected void paintComponent(Graphics g) {
 44             super.paintComponents(g);
 45             this.setBackground(Color.WHITE);
 46             Date.header.paintIcon(this,g,25,11);
 47             g.fillRect(25,75,850,600);
 48             g.setColor(Color.cyan);
 49             g.setFont(new Font("微软雅黑",Font.BOLD,18));
 50             g.drawString("长度"+length,750,35);
 51             g.drawString("分数"+socer,750,55);
 52             Date.food.paintIcon(this,g,foodx,foody);
 53             if(fx.equals("R")){
 54                 Date.right.paintIcon(this,g,snakeX[0],snakeY[0]);//
 55             }else if(fx.equals("U")){
 56                 Date.up.paintIcon(this,g,snakeX[0],snakeY[0]);//
 57             }else if(fx.equals("D")){
 58                 Date.down.paintIcon(this,g,snakeX[0],snakeY[0]);//
 59             }else if (fx.equals("L")){
 60                 Date.left.paintIcon(this,g,snakeX[0],snakeY[0]);//
 61             }
 62 
 63             for (int i = 1; i < length; i++) {
 64                 Date.body.paintIcon(this,g,snakeX[i],snakeY[i]);//身体1
 65             }
 66 
 67         if (isStart == false) {
 68             g.setColor(Color.cyan);
 69             g.setFont(new Font("微软雅黑",Font.BOLD,40));
 70             g.drawString("按下空格开始游戏",300,300);
 71         }
 72         if (isFail) {
 73             g.setColor(Color.RED);
 74             g.setFont(new Font("微软雅黑",Font.BOLD,40));
 75             g.drawString("失败了,按下空格重新开始游戏",300,300);
 76         }
 77     }
 78 //键盘事件监听
 79     @Override
 80     public void keyPressed(KeyEvent e) {
 81         int keyCode = e.getKeyCode();//获得键盘按键
 82         if(keyCode==KeyEvent.VK_SPACE){
 83             if (isFail){
 84                 isFail = false;
 85                 init();
 86             }else {
 87                 isStart = !isStart;
 88             }
 89             repaint(); //重新绘制
 90         }
 91         if (keyCode==KeyEvent.VK_UP){
 92                 fx = "U";
 93         }else if (keyCode==KeyEvent.VK_DOWN){
 94             fx = "D";
 95         }else if (keyCode==KeyEvent.VK_LEFT){
 96             fx = "L";
 97         }else if (keyCode==KeyEvent.VK_RIGHT){
 98             fx = "R";
 99         }
100     }
101 //事件监听(定时器)
102     @Override
103     public void actionPerformed(ActionEvent e) {
104         if(isStart && isFail == false){
105             if (snakeX[0]==foodx&&snakeY[0]==foody){
106                 length++;
107                 socer+=10;
108                 foodx = 25+25*random.nextInt(34);
109                 foody = 75+25*random.nextInt(34);
110             }
111             //身体增长
112             for (int i = length - 1; i > 0 ; i--) {
113                 snakeX[i]=snakeX[i-1];
114                 snakeY[i]=snakeY[i-1];
115             }
116             if (fx.equals("R")){
117                 snakeX[0]=snakeX[0]+25;
118                 if (snakeX[0]>850){ snakeX[0]=25;}
119             }else  if (fx.equals("L")){
120                 snakeX[0]=snakeX[0]-25;
121                 if (snakeX[0]<25){ snakeX[0]=850;}
122             }else  if (fx.equals("U")){
123                 snakeY[0]=snakeY[0]-25;
124                 if (snakeY[0]<75){ snakeY[0]=650;}
125             }else  if (fx.equals("D")){
126                 snakeY[0]=snakeY[0]+25;
127                 if (snakeY[0]>650){ snakeY[0]=75;}
128             }
129             //失败判定
130             for (int i = 1; i < length; i++) {
131                 if (snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
132                     isFail = true;
133                 }
134             }
135 
136             repaint();
137         }
138         timer.start();//定时器开启
139     }
140     @Override
141     public void keyTyped(KeyEvent e) {
142 
143     }
144     @Override
145     public void keyReleased(KeyEvent e) {
146 
147     }
148 }

图片资源

package com.dong.sanke;

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

public class Date {
    public static URL headerURL= Date.class.getResource("statics/header.png");
    public static ImageIcon header= new ImageIcon(headerURL);
    public static URL upURL= Date.class.getResource("statics/up.png");
    public static ImageIcon up= new ImageIcon(upURL);
    public static URL downURL= Date.class.getResource("Statics/down.png");
    public static ImageIcon down= new ImageIcon(downURL);
    public static URL leftURL= Date.class.getResource("statics/left.png");
    public static ImageIcon left= new ImageIcon(leftURL);
    public static URL rightURL= Date.class.getResource("statics/right.png");
    public static ImageIcon right= new ImageIcon(rightURL);
    public static URL bodyURL= Date.class.getResource("statics/body.png");
    public static ImageIcon body= new ImageIcon(bodyURL);
    public static URL foodURL= Date.class.getResource("statics/food.png");
    public static ImageIcon food= new ImageIcon(foodURL);
}

 

posted @ 2021-04-01 23:25  斯卡哈  阅读(104)  评论(0)    收藏  举报