GUI编程

GUI编程

  • 图形用户界面编程

  • GUI核心技术:Swing AWT
  • 为什么学习
    • 写一些小工具
    • 了解MVC,了解监听

AWT

  • 简介

    • 包含了很多的类与接口
    • 元素:窗口,按钮,文本框
    • java.awt
  • 组件与容器

    • Frame
    package com.taidou;
    
    import java.awt.*;
    
    public class testFrame {
        public static void main(String[] args) {
            Frame frame = new Frame("我的第一个Frame窗口");
            //设置窗口可见性
            frame.setVisible(true);
    
            //设置窗口大小
            frame.setSize(500,500);
    
            //设置背景颜色
            frame.setBackground(Color.blue);
    
            //设置初始位置
            frame.setLocation(200,200);
    
            //设置固定大小
            frame.setResizable(false);
        }
    }
    

    image-20200219123932780

    • 面板panel

      • 面板相当于在Frame里面的小Frame设置与Frame类似,设置好最后把它加入到Frame内就行

        package com.taidou;
        
        import java.awt.*;
        import java.awt.event.WindowAdapter;
        import java.awt.event.WindowEvent;
        import java.awt.event.WindowListener;
        
        public class testPanel {
            public static void main(String[] args) {
                Frame frame = new Frame("Frame窗口Panel");
                Panel panel = new Panel();
        
                //设置布局
                frame.setLayout(null);
        
                frame.setBounds(200,200,500,500);
                frame.setBackground(Color.blue);
        
                panel.setBounds(50,50,100,100);
                panel.setBackground(Color.red);
        
                //把panel加入到frame中
                frame.add(panel);
        
                frame.setVisible(true);
        
                //监听事件,监听关闭
                frame.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                });
            }
        }
        

        image-20200219123958929

布局管理器

  • 流式布局

    package com.taidou;
    
    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("FlowLayout");
    
            //按钮
            Button button1 = new Button("button1");
            Button button2 = new Button("button2");
            Button button3 = new Button("button3");
    
            //设置流布局                     设置对齐方式
            frame.setLayout(new FlowLayout(FlowLayout.LEFT));
    
            frame.setSize(400,400);
    
            frame.add(button1);
            frame.add(button2);
            frame.add(button3);
    
            frame.setVisible(true);
    
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
    
        }
    }
    

    image-20200219124103260

  • 东南西北中

    package com.taidou;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    public class TestBorderLayout {
        public static void main(String[] args) {
            Frame frame = new Frame("BorderLayout");
    
            //按钮
            Button button1 = new Button("button1");
            Button button2 = new Button("button2");
            Button button3 = new Button("button3");
            Button button4 = new Button("button4");
            Button button5 = new Button("button5");
    
            frame.add(button1,BorderLayout.EAST);
            frame.add(button2,BorderLayout.NORTH);
            frame.add(button3,BorderLayout.SOUTH);
            frame.add(button4,BorderLayout.WEST);
            frame.add(button5,BorderLayout.CENTER);
    
    
            frame.setSize(400,400);
    
            frame.setVisible(true);
    
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
    
        }
    }
    

    image-20200219124158178

  • 表格布局

    package com.taidou;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    public class TestGridLayout {
        public static void main(String[] args) {
            Frame frame = new Frame("GridLayout");
    
            //按钮
            Button button1 = new Button("button1");
            Button button2 = new Button("button2");
            Button button3 = new Button("button3");
            Button button4 = new Button("button4");
            Button button5 = new Button("button5");
            Button button6 = new Button("button6");
    
            //设置布局为表格布局,3行2列 表格自动填充
            frame.setLayout(new GridLayout(3,2));
            frame.add(button1);
            frame.add(button2);
            frame.add(button3);
            frame.add(button4);
            frame.add(button5);
            frame.add(button6);
    
    
            frame.setSize(400,400);
    
            frame.setVisible(true);
    
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
    
        }
    }
    

    image-20200219124237932

事件监听

  • 事件监听
    • 某件事发生时做什么,例如点击关闭按钮关闭窗口
    • 事件有很多:点击、双击、键盘输入、文本框失去焦点等等等
package com.taidou;

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

public class TestListener {
    public static void main(String[] args) {
        Frame frame = new Frame("Listener");

        Button button = new Button("out");
        Button button2 = new Button("button2");

        //设置按钮标识
        button.setActionCommand("out");

        //创建监听事件
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);
        button2.addActionListener(myActionListener);

        frame.setLayout(new FlowLayout());
        frame.add(button);
        frame.add(button2);

        frame.setSize(200,200);
        frame.setVisible(true);
    }

}

//创建一个监听方法,用于监听事件
class MyActionListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("out")){
            System.out.println("out被点击"+e.getActionCommand());
        }else {
            System.out.println("其他按钮被点击"+e.getActionCommand());
        }
    }
}

image-20200219163138729image-20200219163158739

文本框监听

package com.taidou;

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

public class TestText {
    public static void main(String[] args) {
        new MyFrame();
    }
}

class MyFrame extends Frame{
    public MyFrame(){
        //创建一个文本框
        TextField textField = new TextField();
        add(textField);
        
        
        MyActionListener2 myActionListener2 = new MyActionListener2();
        //文本框的监听事件按下Enter键触发
        textField.addActionListener(myActionListener2);

        setVisible(true);
        pack();

    }
}

class MyActionListener2 implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        //获取信息转换为文本框格式
        TextField textField = (TextField) e.getSource();
        System.out.println(textField.getText());
    }
}

image-20200219165324778image-20200219165353825

简易计算器,组合和内部类

初始代码

package com.taidou.demo2;

import org.omg.CORBA.INTERNAL;

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

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        new Calc();
    }
}

//计算器类
class Calc extends Frame{
    public Calc(){
        //三个文本框
        TextField num1 = new TextField(10);
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(20);
        //一个按钮
        Button button = new Button("=");
        button.addActionListener(new MyCalcListener(num1,num2,num3));
        //一个标签
        Label label = new Label("+");


        //布局
        setLayout(new FlowLayout());

        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);


    }

}


//监听类
class MyCalcListener implements ActionListener {
    TextField num1,num2,num3;

    public MyCalcListener(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,num2
        num1.setText("");
        num2.setText("");

    }
}

通过组合改造为面向对象写法

package com.taidou.demo2;

import org.omg.CORBA.INTERNAL;

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

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        new Calc().loadFrame();
    }
}

//计算器类
class Calc 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 MyCalcListener(this));
        //一个标签
        Label label = new Label("+");


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

        pack();
        setVisible(true);
    }

}


//监听类
class MyCalcListener implements ActionListener {
    //获取计算器对象,在一个类中组合另一个类
    Calc calc = null;

    public MyCalcListener(Calc calc) {
        this.calc = calc;
    }

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

        //加法运算
        calc.num3.setText(""+(n1+n2));

        //清空num1,num2
        calc.num1.setText("");
        calc.num2.setText("");

    }
}

使用内部类再次改造

package com.taidou.demo2;

import org.omg.CORBA.INTERNAL;

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

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        new Calc().loadFrame();
    }
}


//计算器类
class Calc 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 MyCalcListener());
        //一个标签
        Label label = new Label("+");


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

        pack();
        setVisible(true);
    }
    
    //监听类
    //内部类最大的好处就是可以畅通无阻的访问外类的属性与方法
    class MyCalcListener 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,num2
            num1.setText("");
            num2.setText("");

        }
    }
}


画笔

  • 可以在窗口里画图形
  • 可以使用画笔实现动态
package com.taidou.demo3;

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,500,500);
        setVisible(true);
    }
    @Override
    public void paint(Graphics g) {
        g.setColor(Color.red);//设置画笔颜色
        g.fillOval(50,50,100,100);//画一个实心圆

        g.setColor(Color.yellow);
        g.fillRect(150,50,100,100);//画一个实心矩形
    }
}

image-20200220120030641

### 鼠标监听

  • 监听鼠标的操作

  • 在鼠标点击的位置画一个点

package com.taidou.demo3;

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

public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("画图");
    }
}

class MyFrame extends Frame{
    //创建一个集合存储点
    ArrayList points;
    public MyFrame(String title){
        super(title);
        points = new ArrayList();
        setBounds(100,100,500,500);
        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.fillOval(point.x-5,point.y-5,10,10);
        }
    }

    class MyMouseListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent e) {
            //存储鼠标点击的位置
            Point point = new Point(e.getX(),e.getY());
            points.add(point);

            //每次点击后重画
            repaint();
        }
    }
}

image-20200220124220988

监听窗口

  • 监听窗口的一些状态
package com.taidou.demo3;

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(){
        setBounds(100,100,200,200);
        setVisible(true);


        this.addWindowListener(new WindowAdapter() {
            @Override //监听窗口打开
            public void windowOpened(WindowEvent e) {
                super.windowOpened(e);
            }

            @Override //监听窗口关闭按钮
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

键盘监听

  • 监听你按了哪一个键
  • 在KeyEvent里面存储了所有键对应值的常量,VK开头例如上键(VK_UP)
package com.taidou.demo3;

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

public class TestKey {
    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame{
    public KeyFrame(){
        setBounds(100,100,200,200);
        setVisible(true);

        this.addKeyListener(new KeyAdapter() {
            //键盘按下
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                //判断是否是按下上键
                if (keyCode==KeyEvent.VK_UP){
                 }
            }
        });
    }
}

Swing

  • Swing与AWT区别不大,是在其基础上增加的一些内容

窗口

  • AWT为Frame,Swing为Jframe
  • 所有设置与Frame基本相同
package com.taidou.demo4;

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

public class TestJframe {
    public static void main(String[] args) {
        new MyJframe();
    }
}
class MyJframe extends JFrame{
    public MyJframe(){
        setVisible(true);
        setBounds(100,100,200,200);

        //Jframe窗体设置需要先获取容器
        Container contentPane = getContentPane();
        contentPane.setBackground(Color.blue);

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

弹窗

  • JDialog,默认有关闭事件
package com.taidou.demo4;

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

public class TestJDialog extends JFrame {
    public static void main(String[] args) {
        new TestJDialog();
    }

    //主窗口
    public TestJDialog(){
        setVisible(true);
        setBounds(100,100,200,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

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

        //按钮
        JButton button = new JButton("弹窗");
        button.setBounds(20,20,100,20);
        contentPane.add(button);

        //监听按钮,控制弹窗弹出
        button.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyDialog();
            }
        });

    }
}

//弹窗
class MyDialog extends JDialog{
    public MyDialog() {
        //设置弹窗的属性
        setVisible(true);
        setBounds(300,300,100,100);
        Container contentPane = getContentPane();

        JLabel label = new JLabel("这是弹窗");

        contentPane.add(label);
    }
}

image-20200220144536327

标签

label

JLabel label = new JLabel();

图标icon

package com.taidou.demo4;

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

public class TestIcon extends JFrame implements Icon {

    private int w;
    private int h;

    public TestIcon(){
    }

    public TestIcon(int w, int h){
        this.w = w;
        this.h = h;
    }

    public void init(){
        TestIcon testIcon = new TestIcon(10,10);
        JLabel label = new JLabel("图标", testIcon, SwingConstants.CENTER);

        Container contentPane = getContentPane();
        contentPane.add(label);

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

    }

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

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

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

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

image-20200220153017433

图片icon

package com.taidou.demo4;

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

public class ImgIcon extends JFrame {

    public ImgIcon(){
        //获取图片地址
        URL url = ImgIcon.class.getResource("tx.PNG");
        ImageIcon imageIcon = new ImageIcon(url);
        JLabel label = new JLabel("imgIcon",imageIcon,SwingConstants.CENTER);

        Container contentPane = getContentPane();
        contentPane.add(label);

        setBounds(0,0,700,700);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

image-20200220154303607

面板

  • Jpanel
JPanel panel = new JPanel();
  • JScrollPane
  • 有滚动条的面板
package com.taidou.demo4;

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

public class TestJScrollPane extends JFrame {
    public TestJScrollPane(){
        Container contentPane = getContentPane();

        //文本域
        JTextArea textArea = new JTextArea(20,50);

        JScrollPane jScrollPane = new JScrollPane(textArea);
        contentPane.add(jScrollPane);

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

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

image-20200220172926266

按钮

  • 普通按钮
    • 可以在括号了吗加入图片标签变成图片按钮
JButton jButton = new JButton();
  • 单选按钮
    • 单选按钮需要分组,一组的按钮只能选择其中一个
JRadioButton jRadioButton1 = new JRadioButton();
JRadioButton jRadioButton2 = new JRadioButton();
JRadioButton jRadioButton3 = new JRadioButton();
//分组
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(jRadioButton1);
buttonGroup.add(jRadioButton2);
buttonGroup.add(jRadioButton3);
  • 多选按钮
JCheckBox jCheckBox1 = new JCheckBox();
JCheckBox jCheckBox2 = new JCheckBox();

列表

  • 下拉框
package com.taidou.demo5;

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

public class TestComboBox extends JFrame {
    public TestComboBox(){
        Container contentPane = getContentPane();

        //创建下拉框
        JComboBox jComboBox = new JComboBox();
        //加入选项信息
        jComboBox.addItem("1111");
        jComboBox.addItem("2222");
        jComboBox.addItem("3333");
        jComboBox.addItem("4444");

        contentPane.add(jComboBox);

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

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

image-20200220195225226

  • 列表框
package com.taidou.demo5;

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

public class TestList extends JFrame {
    public TestList(){
        Container contentPane = getContentPane();

        //列表信息
        String[] str = {"1111","2222","3333"};
        //创建列表框
        JList jList = new JList(str);

        contentPane.add(jList);

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

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

image-20200220195600880

文本框

  • 文本框
JTextField jTextField = new JTextField();
  • 密码框
JPasswordField jPasswordField = new JPasswordField();
  • 文本域
JTextArea jTextArea = new JTextArea();

贪吃蛇游戏

  • 源码结构

image-20200221194048321

  • Data类用于把用到的素材导入转换
  • StartGame类是主启动类
  • GamePanel类是主面板和逻辑

Data

package com.taidou.snake;

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

public class Data {

    //把需要的素材导入
    public static URL headUURL = Data.class.getResource("/img/head_u.png");
    public static URL headDURL = Data.class.getResource("/img/head_d.png");
    public static URL headLURL = Data.class.getResource("/img/head_l.png");
    public static URL headRURL = Data.class.getResource("/img/head_r.png");
    public static ImageIcon headu = new ImageIcon(headUURL);
    public static ImageIcon headd = new ImageIcon(headDURL);
    public static ImageIcon headl = new ImageIcon(headLURL);
    public static ImageIcon headr = new ImageIcon(headRURL);


    public static URL bodyURL = Data.class.getResource("/img/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);

    public static URL foodURL = Data.class.getResource("/img/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);

}

StartGame

package com.taidou.snake;

import javax.swing.*;

//游戏启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new GamePanel());

        frame.setResizable(false);
        frame.setBounds(0,0,800,660);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}

GamePanel

package com.taidou.snake;

import javafx.scene.image.Image;

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 ltngth ;
    int[] snakeX = new int[500];
    int[] snakeY = new int[500];

    String fx;//头朝向的方向

    //游戏状态
    boolean isStart = false;
    boolean isLose = false;

    Timer timer = new Timer(100,this);

    //食物的数据
    int foodX;
    int foodY;
    Random random = new Random();

    //积分
    int score;

    public GamePanel() {
        init();
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();
    }

    //初始化方法
    public void init(){
        ltngth = 3;
        snakeX[0] = 200;snakeY[0] = 582;//头的初始位置
        snakeX[1] = 175;snakeY[1] = 582;//第一节身体的位置
        snakeX[2] = 150;snakeY[2] = 582;//第二节身体的位置

        fx = "R";

        //初始化食物初始位置
        foodX = 25 + 25 * random.nextInt(30);
        foodY = 107 + 25 * random.nextInt(20);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.white);
        g.fillRect(25,0,750,100);//顶部信息栏
        g.fillRect(25,107,750,500);//游戏界面

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

        //画蛇
        if(fx.equals("U")){
            Data.headu.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("D")){
            Data.headd.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("R")){
            Data.headr.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("L")){
            Data.headl.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        
        for (int i = 1; i < ltngth; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }


        //顶部信息
        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑",Font.BOLD,80));
        g.drawString("贪吃蛇",200,77);
        g.setFont(new Font("微软雅黑",Font.BOLD,20));
        g.drawString("长度:"+ltngth,500,40);
        g.drawString("得分:"+score*10,500,77);



        //暂停文字
        if(isStart == false && isLose == false){
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("按下空格开始游戏",250,300);
        }

        //失败文字
        if(isLose){
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("失败,空格重新开始",250,300);
        }


    }



    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//获得按下的键
        if (keyCode==KeyEvent.VK_SPACE){//如果按下空格键
            if (isLose){
                isLose =false;
                init();//失败初始化游戏状态
            }else {
                isStart = !isStart;//取反改变游戏状态
            }

            repaint();
        }

        //监听键盘 改变方向
        if(keyCode==KeyEvent.VK_UP && fx!="D"){
            fx="U";
        }else if (keyCode==KeyEvent.VK_DOWN && fx!="U"){
            fx="D";
        }else if (keyCode==KeyEvent.VK_LEFT && fx!="R"){
            fx="L";
        }else if (keyCode==KeyEvent.VK_RIGHT && fx!="L"){
            fx="R";
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && isLose == false){
            for (int i = ltngth-1; i > 0; i--) {
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }

            //吃食物
            if (snakeX[0]==foodX && snakeY[0] == foodY){
                ltngth++;
                score++;
                foodX = 25 + 25 * random.nextInt(30);
                foodY = 107 + 25 * random.nextInt(20);

            }

            //穿越边界
            if(fx.equals("U")){
                snakeY[0] = snakeY[0]-25;
                if(snakeY[0]<107){snakeY[0]=582;}
            }else if (fx.equals("D")){
                snakeY[0] = snakeY[0]+25;
                if(snakeY[0]>582){snakeY[0]=107;}
            }else if (fx.equals("R")){
                snakeX[0] = snakeX[0]+25;
                if(snakeX[0]>750){snakeX[0]=25;}
            }else if (fx.equals("L")){
                snakeX[0] = snakeX[0]-25;
                if(snakeX[0]<25){snakeX[0]=750;}
            }

            //失败判定
            for (int i = 1; i < ltngth; i++) {
                if (snakeX[0]==snakeX[i] && snakeY[0] == snakeY[i]){
                    isLose=true;
                }
            }



            repaint();
        }
    }


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


}

猜你喜欢

转载自www.cnblogs.com/taidou-hth/p/12347007.html