GUI编程

GUI编程

​ java基于Swing和AWT技术进行的图形界面化开发,但是由于界面不太美观,并且运行需要JRE环境,没有流行起来,但依旧可以从中了解mvc架构,组件的思想。

1.AWT

1.1 AWT介绍

AWT:抽象窗口工具,其中包含了很多类和接口。

1.2 组件与容器

1.Frame窗口

package gui;

import java.awt.*;

/**
 * 创建一个frame弹窗
 */
public class TestFrame {

    public static void main(String[] args) {
        //创建弹窗并设置标题
        Frame frame = new Frame("我的第一个弹窗");
        //设置弹窗的可见性
        frame.setVisible(true);
        //设置弹窗宽高
        frame.setSize(400,400);
        //设置弹窗背景颜色
        frame.setBackground(Color.CYAN);
        //设置弹窗的起始位置 起始位置处于屏幕的左上角
        frame.setLocation(400,200);
        //设置弹窗固定大小
        frame.setResizable(false);
    }
}

package gui;

import java.awt.*;

/**
 * 测试生成多个frame窗口
 */
public class TestFrame2 {
    public static void main(String[] args) {

        new MyFrame(100,100,200,200,Color.BLACK);
        new MyFrame(100,300,200,200,Color.blue);
        new MyFrame(300,100,200,200,Color.GREEN);
        new MyFrame(300,300,200,200,Color.red);

    }

}

class MyFrame extends Frame{
    //用于记录当前窗口的数量
    private static int id=0;

    public MyFrame(int x,int y,int w,int h,Color color){
        super("我的第"+(++id)+"个窗口");
        //设置窗口的可见性
        setVisible(true);
        //设置窗口起始位置,大小
        setBounds(x,y,w,h);
        //设置窗口颜色
        setBackground(color);
        //设置窗口固定大小
        setResizable(false);
    }
}

2.Panel面板

package gui;

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

/**
 * 测试创建一个面板
 */
public class TestPanel {

    public static void main(String[] args) {
        //面板不能独立存在,需要有一个窗口来承载
        Frame frame = new Frame();
        //设置窗口属性
        frame.setVisible(true);
        frame.setBounds(200,200,600,600);
        frame.setResizable(false);
        frame.setBackground(new Color(220, 204, 197));
        //设置布局为空,否则窗口会被面板完全填充
        frame.setLayout(null);

        //创建面板
        Panel panel = new Panel();
        //面板所在位置,处于窗口中的相对位置
        panel.setBounds(50,50,400,400);
        //panel.setVisible(true);
        panel.setBackground(new Color(31, 97, 186));

        //将面板添加到弹窗中,由于panel继承Container继承Component
        frame.add(panel);

        //添加面板监听事件,点击x关闭页面
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

3.布局管理器

3.1 布局方式

  • FlowLayout 流式布局
  • BorderLayout 边界布局
  • GridLayout 表格布局
package gui;

import java.awt.*;

/**
 * 布局管理器: 流式布局
 */
public class TestFlowLayout {

    public static void main(String[] args) {

        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setBounds(200,200,600,600);

        Button buttona = new Button("按钮A");
        Button buttonb = new Button("按钮B");
        Button buttonc = new Button("按钮C");
        Button buttond = new Button("按钮D");
        Button buttone = new Button("按钮E");
        Button buttonf = new Button("按钮F");

        frame.add(buttona);
        frame.add(buttonb);
        frame.add(buttonc);
        frame.add(buttond);
        frame.add(buttone);
        frame.add(buttonf);

        //设置窗口为流式布局 可以设置起始位置居中、居左、居右,默认居中
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
    }
}

package gui;

import java.awt.*;

/**
 * 布局管理器:border布局
 */
public class TestBorderLayout {
    public static void main(String[] args) {

        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setBounds(200,200,600,600);

        Button buttona = new Button("按钮A");
        Button buttonb = new Button("按钮B");
        Button buttonc = new Button("按钮C");
        Button buttond = new Button("按钮D");
        Button buttone = new Button("按钮E");

        //像弹框中添加按钮时,添加对组件的约束(布局方式)
        frame.add(buttona,BorderLayout.EAST);
        frame.add(buttonb,BorderLayout.WEST);
        frame.add(buttonc,BorderLayout.SOUTH);
        frame.add(buttond,BorderLayout.NORTH);
        frame.add(buttone,BorderLayout.CENTER);


    }


}

package gui;

import java.awt.*;

/**
 * 布局管理器:表格布局
 */
public class TestGridLayout {

    public static void main(String[] args) {

        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setBounds(200,200,600,600);

        Button buttona = new Button("按钮A");
        Button buttonb = new Button("按钮B");
        Button buttonc = new Button("按钮C");
        Button buttond = new Button("按钮D");
        Button buttone = new Button("按钮E");
        Button buttonf = new Button("按钮F");

        frame.add(buttona);
        frame.add(buttonb);
        frame.add(buttonc);
        frame.add(buttond);
        frame.add(buttone);
        frame.add(buttonf);

        //设置2行3列,行间距
        frame.setLayout(new GridLayout(2,3,20,20));

    }

}

3.2布局的组合嵌套

package gui;

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

/**
 * 测试布局的嵌套
 */
public class TestLayout {
    public static void main(String[] args) {

        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setBounds(200,200,600,600);
        frame.setResizable(false);
        //设置窗口为2行一列
        frame.setLayout(new GridLayout(2,1));

        //窗口上面的面板
        Panel p1 = new Panel(new BorderLayout());
        //左右添加按钮
        p1.add(new Button("按钮"),BorderLayout.EAST);
        p1.add(new Button("按钮"),BorderLayout.WEST);
        //上面面板的中间面板
        Panel p2 = new Panel();
        p2.setLayout(new GridLayout(2,1));
        for (int i = 0; i < 2; i++) {
            p2.add(new Button("按钮"));
        }
        p1.add(p2);



        //窗口下面的面板
        Panel p3 = new Panel(new BorderLayout());
        //左右添加按钮
        p3.add(new Button("按钮"),BorderLayout.EAST);
        p3.add(new Button("按钮"),BorderLayout.WEST);
        //下面面板的中间面板
        Panel p4 = new Panel();
        p4.setLayout(new GridLayout(2,2));
        for (int i = 0; i < 4; i++) {
            p4.add(new Button("按钮"));
        }
        p3.add(p4);

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

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

    }
}

4.总结

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

1.3 事件监听

  • button 按钮
  • textField 单行文本
  • label 标签
package gui;

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("事件监听");
        frame.setBounds(200,200,600,400);
        frame.setVisible(true);
        frame.setLayout(new GridLayout(2,1));

        Panel p1= new Panel(new GridLayout(1,2));
        Button button1 = new Button("开始");
        Button button2 = new Button("结束");
        MyActionListener actionListener = new MyActionListener();
        button1.addActionListener(actionListener);
        button2.addActionListener(actionListener);

        p1.add(button1);
        p1.add(button2);

        //文本框点击enter键后,出发监听事件
        TextField textField = new TextField();
        textField.addActionListener(actionListener);

        frame.add(p1);
        frame.add(textField);



        //frame.pack();

    }

}

class MyActionListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        if(actionCommand.equals("开始")){
            System.out.println("点击了开始按钮");
        }else if(actionCommand.equals("结束")){
            System.out.println("点击了结束按钮");
        }else{
            System.out.println(e.getActionCommand());
            e.setSource("");
        }

    }
}

package gui;

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

/**
 * 测试 生成一个简单的计算器
 */
public class TestCalc {
    public static void main(String[] args) {
        new MyCalculator();
    }
}


class MyCalculator extends Frame{

    //定义加数、被加数、和
    TextField num1 = new TextField(10);
    TextField num2 = new TextField(10);
    TextField num3 = new TextField(20);
    //"="按钮
    Button button = new Button("=");


    public MyCalculator(){
        setVisible(true);
        setLayout(new FlowLayout());
        add(num1);
        add(new Label("+"));
        add(num2);
        add(button);
        add(num3);
        pack();

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

    }


    public  void loadFrame(){
        this.button.addActionListener(new MyCalcActionListener());
    }

    private class MyCalcActionListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            num3.setText(Integer.parseInt(num1.getText())+Integer.parseInt(num2.getText())+"");
            num1.setText("");
            num2.setText("");
        }
    }

}

1.4 画笔

package gui;

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,600,400);
        setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        //设置画笔颜色,每次使用完画笔后,最好将画笔颜色置为默认颜色(黑色)
        g.setColor(Color.red);
        //画一个红色实心的圆
        g.fillOval(50,50,200,200);
    }
}

1.5 窗口、鼠标、键盘监听事件

package gui;

import java.awt.*;
import java.awt.event.*;

/**
 * 测试窗口、鼠标、键盘监听事件
 */
public class TestMouseListener {
    public static void main(String[] args) {
        Frame frame = new Frame("鼠标监听测试");
        frame.setBounds(200,200,600,400);
        frame.setVisible(true);
        //添加鼠标监听事件,内部类
        //frame.addMouseListener(new MyMouseListener());
        //匿名内部类实现
        frame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("点击了鼠标");
            }

            @Override
            public void mousePressed(MouseEvent e) {
                System.out.println("按压了鼠标");
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                System.out.println("鼠标移入");
            }

            @Override
            public void mouseExited(MouseEvent e) {
                System.out.println("鼠标移出");
            }
        });

        //添加窗口监听事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("点击窗口“X”,关闭窗口。");
            }

            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("离开窗口后再次点击窗口时,窗口激活!");
            }
        });

        //添加键盘监听事件
        frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
               //获取当前按下的键值(数字,无需记忆,使用对应键名称即可)
                int keyCode = e.getKeyCode();
                if(keyCode == KeyEvent.VK_UP){
                    System.out.println("你按下了上键。");
                }
            }
        });

    }

    //适配器模式,使用哪个方法就重写哪个方法
    public static class MyMouseListener extends MouseAdapter{
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("点击了一次鼠标");
            System.out.println("点击坐标("+e.getX()+","+e.getY()+")");
        }
    }
    
}



2.SWING

​ awt的进阶,相比于awt多了很多默认的方法,便于设计页面操作。

2.1 JFrame窗口

package gui.swing;

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

/**
 * 测试Jframe窗口
 */
public class TestJFrame {

    public static void main(String[] args) {

        JFrame jFrame = new JFrame("我的JFrame窗口!");
        jFrame.setVisible(true);
        jFrame.setBounds(200,200,600,400);
        //设置背景颜色 JFrame窗口设置背景颜色不同的是,需要先获取当前窗口对应的容器,对容器设置背景颜色
        Container container = jFrame.getContentPane();
        container.setBackground(Color.CYAN);
        //设置一个label并居中显示
        JLabel jLable = new JLabel("测试JLable");
        //Swing类的常量设置
        jLable.setHorizontalAlignment(SwingConstants.CENTER);
        jFrame.add(jLable);
        //设置窗口的关闭事件 关闭窗口时程序关闭
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }

}

2.2 JDialog弹窗

package gui.swing;

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

/**
 * 测试JDialog弹窗
 */
public class TestJDialog {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("我的JFrame窗口!");
        jFrame.setVisible(true);
        jFrame.setBounds(200,200,600,400);
        //设置窗口的关闭事件 关闭窗口时程序关闭 windows常量设置
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //添加弹窗
        JDialog jDialog = new JDialog(jFrame,"我的JDialog弹窗");
        //添加按钮,绑定事件弹出弹窗
        JButton button = new JButton("点击弹出弹窗");
        button.setBounds(50,50,200,100);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jDialog.setVisible(true);
                Container container = jDialog.getContentPane();
                container.setBackground(Color.yellow);
                jDialog.setBounds(100,100,400,200);
                //dialog弹窗自带关闭窗口事件,不必重复添加
            }
        });
        //设置窗口绝对定位,窗口内的内容随意摆放
        jFrame.setLayout(null);
        jFrame.add(button);
        
    }

}

2.3 Icon图标

package gui.swing;

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

/**
 * 测试生成一个图标
 */
public class TestIcon  implements Icon  {

    public static void main(String[] args) throws MalformedURLException {
        //自定义画一个圆形图标
        TestIcon testIcon = new TestIcon();
        JFrame jFrame = JFrameUtils.getJrame();
        //将图标添加到标签中并定义位置
        JLabel jLabel = new JLabel("标签", testIcon, SwingConstants.CENTER);
        jFrame.add(jLabel);

        JButton button = new JButton("按钮");
        button.setBounds(100,100,200,100);
        URL url = TestIcon.class.getResource("/tb.jpg");
        //图片图标
        ImageIcon imageIcon = new ImageIcon(url);
        JLabel jLabel2 = new JLabel("标签", imageIcon, SwingConstants.CENTER);
        jFrame.add(jLabel2);
        
    }


    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.setColor(Color.BLUE);
        g.fillOval(x,y,100,100);

    }

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

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

}

2.4 Jsroll面板

package gui.swing;

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

/**
 * 测试带有滑动条的面板
 */
public class TestScrolPanel extends JFrame {

    public TestScrolPanel(){
        //创建一个文本域
        JTextArea jTextArea = new JTextArea(20, 50);
        Container container = this.getContentPane();
        //创建一个带有滑动条的面板,并插入文本域
        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        container.add(jScrollPane);
        //对窗口的属性设置,放在窗口其他操作完成后
        setVisible(true);
        setSize(500,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

}

2.5 面板中的常用组件

package gui.swing;

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

/**
 * 测试面板中常用的组件
 */
public class TestCommonComponents extends JFrame {

    public TestCommonComponents(){
        //获取当前容器
        Container container = this.getContentPane();

        //创建一个单选框
        JRadioButton radio1 = new JRadioButton("radio1");
        JRadioButton radio2 = new JRadioButton("radio1");
        JRadioButton radio3 = new JRadioButton("radio1");
        //创建一个单选框组,在同一个组中只能选择一个,否则就可以多选
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(radio1);
        buttonGroup.add(radio2);
        buttonGroup.add(radio3);
        container.add(radio1);
        container.add(radio2);
        container.add(radio3);

        //创建一个多选框
        JCheckBox checkBox1 = new JCheckBox("checkBox1");
        JCheckBox checkBox2 = new JCheckBox("checkBox2");
        JCheckBox checkBox3 = new JCheckBox("checkBox3");
        container.add(checkBox1);
        container.add(checkBox2);
        container.add(checkBox3);

        //创建一个下拉框
        JPanel comboxjPanel = new JPanel();
        String[] nameArr = {"张三","李四","王五"};
        JComboBox jComboBox = new JComboBox(nameArr);
        comboxjPanel.add(jComboBox);
        container.add(comboxjPanel);

        //创建一个列表
        JList jList = new JList(nameArr);
        JPanel listJpanel = new JPanel();
        listJpanel.add(jList);
        container.add(listJpanel);

        //创建一个文本框、密码框、文本域
        JTextField textField = new JTextField("textField", 10);
        JPasswordField jPasswordField = new JPasswordField();
        JTextArea jTextArea = new JTextArea("20");
        JPanel textJpanel = new JPanel();
        textJpanel.add(textField);
        textJpanel.add(jPasswordField);
        textJpanel.add(jTextArea);
        textJpanel.setSize(200,100);
        textJpanel.setLayout(new GridLayout(3,1));
        container.add(textJpanel);

        container.setLayout(new FlowLayout());
        setVisible(true);
        setSize(500,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

}

3.贪吃蛇游戏

package snake;

import javax.swing.*;

/**
 * 贪吃蛇游戏的主启动类
 */
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        //游戏界面绘制都应该在面板中进行
        //添加游戏面板
        frame.add(new GamePanel());

        frame.setBounds(200,200,900,720);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setResizable(false);
    }

}

package 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;

import static javax.swing.text.StyleConstants.Bold;

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

    //定义小蛇的长度
    int length;
    //定义小蛇的x,y坐标,头部和每个身体都有一个坐标,用数组存入
    //数组大小大于面板中游戏区域,但不可小于,否则身体过长会导致数组溢出
    int[] snakex = new int[500];
    int[] snakey = new int[600];
    //小蛇头部的方向 默认是向右的
    String direction;

    //食物的坐标
    int foodx;
    int foody;

    //游戏状态
    boolean startGame = false;
    //失败状态
    boolean isFile = false;

    //设置100ms执行一次
    Timer timer = new Timer(100,this);
    Random random = new Random();

    public GamePanel(){
        //初始化小蛇的数据
        init();
        //添加面板焦点监听
        setFocusable(true);
        //添加键盘事件监听
        addKeyListener(this);
    }


    //初始化小蛇
    public void init(){
        //初始方向向右
        direction = "R";
        //小蛇的长度
        length = 3;
        //位置
        //头部
        snakex[0] = 100;snakey[0] = 100;
        //身体
        snakex[1] = 75;snakey[1] = 100;
        snakex[2] = 50;snakey[2] = 100;

        //食物的坐标随机出现
        //限定在长850,高600的区域内
        foodx = 25 + 25*random.nextInt(34);
        foody = 75 + 25*random.nextInt(24);
        //启动定时器
        timer.start();
    }


    @Override
    protected void paintComponent(Graphics g) {
        //面板中的所有元素,都通过这支画笔画出
        //此处调用原父类方法有清屏效果
        super.paintComponent(g);
        //设置面板颜色背景为黑色
        this.setBackground(Color.BLACK);
        //头部广告位画在面板中
        Data.head.paintIcon(this,g,25,11);
        //游戏主面板的矩形框
        g.fillRect(25,75,850,600);

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

        //画出小蛇
        if(direction.equals("R")){
            Data.right.paintIcon(this,g,snakex[0],snakey[0]);
        }else if(direction.equals("L")){
            Data.left.paintIcon(this,g,snakex[0],snakey[0]);
        }else if(direction.equals("U")){
            Data.up.paintIcon(this,g,snakex[0],snakey[0]);
        }else if(direction.equals("D")){
            Data.down.paintIcon(this,g,snakex[0],snakey[0]);
        }

        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakex[i],snakey[i]);
        }

        if(!startGame && !isFile){
            //画出游戏中的提示信息
            g.setColor(Color.white);
            g.setFont(new Font("宋体",Font.BOLD,40));
            g.drawString("按下空格开始游戏",300,300);
        }

        if(isFile){
            //画出游戏中的提示信息
            g.setColor(Color.RED);
            g.setFont(new Font("宋体",Font.BOLD,40));
            g.drawString("失败,按下空格重新游戏",300,300);
        }




    }

    //添加键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_SPACE){
            //如果按下空格键
            if(isFile){
                //失败状态按下空格键,重置失败状态,重新加载游戏
                isFile = false;
                init();
            }else{
                //暂停或启动游戏
                startGame = !startGame;
            }
            //重新画出面板中的内容
            repaint();
        }

        if(startGame && !isFile){
            if(keyCode == KeyEvent.VK_UP){
                if(!direction.equals("D")){
                    direction = "U";
                }
            }else if(keyCode == KeyEvent.VK_DOWN){
                if(!direction.equals("U")){
                    direction = "D";
                }
            }else if(keyCode == KeyEvent.VK_LEFT){
                if(!direction.equals("R")){
                    direction = "L";
                }
            }else if(keyCode == KeyEvent.VK_RIGHT){
                if(!direction.equals("L")){
                    direction = "R";
                }
            }
        }


    }

    //面板监听
    @Override
    public void actionPerformed(ActionEvent e) {
        if(startGame && isFile == false){
            if(foodx == snakex[0] && foody == snakey[0]){
                length++;
                //重置食物的坐标
                foodx = 25 + 25*random.nextInt(34);
                foody = 25 + 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")){
                if(snakex[0] == 850){
                    //到达边界返回
                    snakex[0] = 25;
                }else{
                    //头部横坐标右移一位
                    snakex[0] = snakex[0]+25;
                }
            }else if(direction.equals("L")){
                if(snakex[0] == 25){
                    snakex[0] = 850;
                }else{
                    //头部横坐标坐移一位
                    snakex[0] = snakex[0]-25;
                }
            }else if(direction.equals("U")){
                if(snakey[0] == 75){
                    snakey[0] = 700;
                }else{
                    //头部横坐标上移一位
                    snakey[0] = snakey[0]-25;
                }
            }else if(direction.equals("D")){
                if(snakey[0] == 650){
                    snakey[0] = 75;
                }else{
                    //头部横坐标下移一位
                    snakey[0] = snakey[0]+25;
                }
            }

        }
        //失败判定
        for (int i = length-1; i >0 ; i--) {
            if(snakex[0] == snakex[i] && snakey[0] == snakey[i]){
                isFile = true;
                init();
            }
        }

        repaint();
        //启动定时器
        timer.start();

    }


    @Override
    public void keyTyped(KeyEvent e) {

    }
    @Override
    public void keyReleased(KeyEvent e) {

    }

}
package snake;

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

/**
 * 加载静态资源的工具类
 */
public class Data {
    //头部
    public static URL headURL = Data.class.getResource("static/header.png");
    public static ImageIcon head = new ImageIcon(headURL);
    //身体
    public static URL bodyURL = Data.class.getResource("static/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
    //食物
    public static URL foodURL = Data.class.getResource("static/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);

    //方向
    public static URL upURL = Data.class.getResource("static/up.png");
    public static URL downURL = Data.class.getResource("static/down.png");
    public static URL leftURL = Data.class.getResource("static/left.png");
    public static URL rightURL = Data.class.getResource("static/right.png");
    public static ImageIcon up = new ImageIcon(upURL);
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);

}

游戏图片素材:图片下载

狂神说视频地址:视频链接

原文地址:http://www.cnblogs.com/lzlbk-321/p/16852762.html

发表评论

您的电子邮箱地址不会被公开。