javaGUI

简介

GUI(图形用户界面)的核心技术:Swing,AWT。

不流行:界面不美观,需要jre环境。

学习GUI:可以写一些小工具,维护swing的界面,了解MVC架构,了解监听。

组件:

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

AWT(抽象的窗口工具)

AWT简介

  1. 包含了很多类和接口

  2. 元素:窗口,按钮,文本框

  3. java.awt

    网图

Frame的使用

public class TestFrame {
    public static void main(String[] args) {
        //Frame.JDK  看源码
        Frame frame = new Frame("我的第一个Java图形界面窗口");
        //需要设置可见性
        frame.setVisible(true);
        //设置窗口大小
        frame.setSize(400, 400);
        //设置背景颜色
        frame.setBackground(new Color(104, 42, 42));
        //弹出初始位置
        frame.setLocation(200,400);
        //设置窗口大小固定
        frame.setResizable(false);
    }
}

问题:窗口无法关闭,需要停止java程序

设置多个窗口:

public class TestFrame {
    public static void main(String[] args) {
        MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.blue);
        MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.yellow);
        MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.pink);
        MyFrame myFrame4= new MyFrame(300, 300, 200, 200, Color.pink);
    }
}

class MyFrame extends Frame {
    
    static int id = 0;//计数窗口个数
    
    public MyFrame(int x, int y, int w, int h, Color color) {
        super("MyFrame" + (++id));
        setBounds(x, y, w, h);//x,y对应Location,w,h对应size
        setBackground(color);
        setVisible(true);
    }
}

面板 panel

public class TestFrame {
    public static void main(String[] args) {

        Frame frame = new Frame();
        //布局的概念
        Panel panel = new Panel();

        //设置布局
        frame.setLayout(null);
        //设置坐标
        frame.setBounds(300, 300, 400, 400);
        //设置颜色
        frame.setBackground(new Color(239, 217, 7, 119));

        //panel设置坐标,相对于Frame
        panel.setBounds(50, 50, 200, 200);
        panel.setBackground(new Color(199, 20, 20));

        frame.add(panel);
        frame.setVisible(true);
    }
}

布局管理器

流式布局

public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        
        //组件-按钮
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        
        //设置为流式布局
        //frame.setLayout(new FlowLayout());
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));//左
        frame.setBounds(200, 200, 300, 300);
        //把按钮添加进去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.setVisible(true);
    }
}

东西南北中

public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        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.setLayout(new BorderLayout());
        frame.setBounds(200, 200, 300, 300);
        //把按钮添加进去,位置对应后面参数对应的位置
        frame.add(button1,BorderLayout.EAST);
        frame.add(button2,BorderLayout.WEST);
        frame.add(button3,BorderLayout.SOUTH);
        frame.add(button4,BorderLayout.NORTH);
        frame.add(button5,BorderLayout.CENTER);
        frame.setVisible(true);
    }
}

表格布局

public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        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 button5 = new Button("button6");
        //设置为表格布局,3行列
        frame.setLayout(new GridLayout(3, 2));
        frame.setBounds(200, 200, 300, 300);
        //把按钮添加进去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);
        frame.pack();//java函数:作用 自动布局,选择一个最好的
        frame.setVisible(true);
    }
}

事件监听

当事情发生的时候,需要干什么?

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 TestFrame {
    public static void main(String[] args) {
        //按下按钮触发一些事件
        Frame frame = new Frame();
        Button button = new Button("button");
        
        //因为addActionListener需要一个ActionListener,所以我们要构造一个
        button.addActionListener(new MyAction());
        frame.setLayout(new BorderLayout());
        frame.add(button, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
        
        //因为窗口关不掉,所以要设置关闭窗口
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

//事件监听
class MyAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("000");
    }
}

文本框(TextField)的监听

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

class MyFrame extends Frame {
    public MyFrame() {
        TextField textField = new TextField();
        add(textField);

        //监听这个文本框的文字,按下enter就会触发这个输入框的事件
        textField.addActionListener(new MyActionListener());

        //设置替换编码,隐藏输入内容
        textField.setEchoChar('*');
        setVisible(true);
        pack();
    }
}

class MyActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        TextField source =(TextField) e.getSource();  //获得资源,返回一个对象
        System.out.println(source.getText());
        source.setText(""); //null,enter后清空文本内容
    }
}

制作简易计算器

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

//一个实现加法的计算器
class MyFrame extends Frame {
    public MyFrame() {
        
        //设置加法所需的文本框和符号
        TextField textField1 = new TextField(10);
        TextField textField2 = new TextField(10);
        TextField textField3 = new TextField(20);
        Button button = new Button("=");
        Label label = new Label("+");
        
        //添加监听事件,流式布局,添加组件
        button.addActionListener(new MyActionListener(textField1, textField2, textField3));
        setLayout(new FlowLayout());
        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);
        setVisible(true);
        pack();
        
    }
}

class MyActionListener implements ActionListener {
    
    private TextField textField1, textField2, textField3;

    public MyActionListener(TextField textField1, TextField textField2, TextField textField3) {
        this.textField1 = textField1;
        this.textField2 = textField2;
        this.textField3 = textField3;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //获取1,2文本框中的数据
        int a = Integer.parseInt(textField1.getText());
        int b = Integer.parseInt(textField2.getText());
        //进行加法运算,并且输入到3文本框内
        textField3.setText("" + (a + b));
        textField1.setText("");
        textField2.setText("");
    }
}

画笔

public class TestFrame {
    public static void main(String[] args) {
        MyPrint myPrint = new MyPrint();
        myPrint.loadFrame();
    }
}

class MyPrint extends Frame {

    //设置frame的位置和大小以及可视性
    public void loadFrame() {
        setBounds(200, 200, 300, 300);
        setVisible(true);
    }

    //画笔
    @Override
    public void paint(Graphics g) {
        //画笔需要有颜色,画笔可以画画
        g.setColor(Color.blue);
        //g.fillOval(100, 100, 100, 100);//实心圆
        //空心的圆
        g.drawOval(100, 100, 100, 100);
    }
}

鼠标监听(模拟画图工具)

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

}

class MyFrame extends Frame{
    
    ArrayList points;
    
    public MyFrame(String title) {
        // TODO Auto-generated constructor stub
        super(title);
        setBounds(200, 200, 400, 400);
        //存鼠标产生的点
        points=new ArrayList<>();
        this.addMouseListener(new MyMouseListener());
        setVisible(true);
    }
    
    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 {
        //按下,弹起,按住不放
        public void mousePressed(MouseEvent e) {
            MyFrame myFrame=(MyFrame)e.getSource();
            //点击的时候,界面上产生一个点
            myFrame.addPaint(new Point(e.getX(),e.getY()));
            //没次点击鼠标都需要重画一遍
            myFrame.repaint();
        }
    }
    
}

CSDN图

窗口监听

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

class WindowFrame extends Frame{
    public WindowFrame() {
        setBackground(Color.blue);
        setBounds(100,100,200,200);
        setVisible(true);

        this.addWindowListener(//this, 就是本身,然后本身加入这个方法,就是匿名内部类
                //匿名内部类,建议这么写
                new WindowAdapter() {
                
                    @Override
                    //关闭窗口
                    public void windowClosing(WindowEvent e) {
                        //super.windowClosing(e);
                        System.out.println("windowClosing");
                        System.exit(0);//0正常退出,1非正常退出
                    }

                    @Override
                    //激活窗口
                    public void windowActivated(WindowEvent e) {
                        //super.windowActivated(e);
                        WindowFrame source = (WindowFrame) e.getSource();
                        source.setTitle("被激活了");
                        System.out.println("windowActivated");//激活
                    }

                }
        );
    }

}

键盘监听

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();//不需要去记这个数值,直接使用静态属性 VK_XXX
                System.out.println(keyCode);
                if (keyCode == KeyEvent.VK_UP){
                    System.out.println("你按下了上键");

                }
                //根据按下不同操作,产生不同结果:
            }
        });
    }
}

Swing

窗口,面板

public class JFrame {

    //init(); 初始化
    public  void init(){
        
        JFrame jf = new JFrame("这是一个JFrame 窗口");
        jf.setVisible(true);
        jf.setBounds(100,100,200,200);
        jf.setBackground(Color.cyan);
        
        //设置文字 Jlabel,标签居中
        JLabel label = new JLabel("阿巴阿巴阿巴",SwingConstants.CENTER);
        jf.add(label);

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

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

弹窗

JDialog,用来被弹出,默认就有关闭事件

//主窗口
public class DialogDemo extends JFrame {

    public DialogDemo() {//构造器
        
        this.setVisible(true);
        this.setBounds(100,100,700,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);
        //this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);// 里面自带了,所以这个是多余的

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

        container.add(new Label("阿巴阿巴阿巴"));

    }
}

标签

//图标,需要实现类,Frame 继承
public class IconDemo 
    extends JFrame 
    implements Icon {
    
    private  int width;
    private int height;

    public IconDemo(){}//无参构造

    public IconDemo(int width, int height){
        this.width = width;
        this.height = height;
    }

    public void init(){
        
        this.setBounds(100,100,700,500);
        IconDemo iconDemo = new IconDemo(15, 15);
        //图标放在标签上,也可以放在按钮上!
        JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);

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

        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

    public void paintIcon(Component c, Graphics g, int x, int y){
        g.fillOval(x,y,width,height);
    }

    public int getIconWidth(){
        return this.width;
    }

    public int getIconHeight(){
        return this.height;
    }
}

图片ICON

public class ImageIconDemo extends JFrame {
    public ImageIconDemo() {
        //获取图片的地址
        JLabel label = new JLabel("ImageIcon");
        URL url = ImageIconDemo.class.getResource("timg.jpg");

        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(100,100,200,200);
    }

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

    }
}

面板

JPanel

public class JPaneDemo extends JFrame {

    public JPaneDemo(){
        Container container = this.getContentPane();

        container.setLayout(new GridLayout(2,1,10,10));//后面的参数的意思,间距

        JPanel panel = new JPanel(new GridLayout(1,3));

        panel.add(new JButton("1"));
        panel.add(new JButton("1"));
        panel.add(new JButton("1"));

        container.add(panel);

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

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

    }
}

JScrollPanel

public class JScrollDemo extends JFrame {

    public JScrollDemo() {
        Container container = this.getContentPane();

        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        textArea.setText("阿巴阿巴阿巴");

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

        this.setVisible(true);
        this.setBounds(100,100,300,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

    }
}

按钮

图片按钮

public class JButtonDemo01 extends JFrame {

    public JButtonDemo01() {
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL url = ImageIconDemo.class.getResource("timg.jpg");

        ImageIcon imageIcon = new ImageIcon(url);

        //把这个图标放在按钮上
        JButton button = new JButton();
        button.setIcon(imageIcon);
        button.setToolTipText("图片按钮");

        //add
        container.add(button);

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

    }

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

    }
}

单项按钮

public class JButtonDemo02 extends JFrame {
    public JButtonDemo02(){
        Container container = this.getContentPane();

        //将一个图片变为图标
        URL url = ImageIconDemo.class.getResource("timg.jpg");
        ImageIcon imageIcon = new ImageIcon(url);

        //单选框
        JRadioButton radioButton1 = new JRadioButton("JRadioButton01");
        JRadioButton radioButton2 = new JRadioButton("JRadioButton02");
        JRadioButton radioButton3 = new JRadioButton("JRadioButton03");

        //由于单选框只能选择一个,所以需要分组,一个组中只能选择一个
        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.setBounds(100,100,500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


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

    }
}

复选按钮

public class JButtonDemo03 extends JFrame {
    public JButtonDemo03(){
        Container container = this.getContentPane();

        //将一个图片变为图标
        URL url = ImageIconDemo.class.getResource("timg.jpg");
        ImageIcon imageIcon = new ImageIcon(url);

        
        //多选框
        JCheckBox checkBox01 = new JCheckBox("checkBox01");
        JCheckBox checkBox02 = new JCheckBox("checkBox02");

        //由于单选框只能选择一个,所以需要分组,一个组中只能选择一个
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        group.add(radioButton3);//如果不加入这个,那就都可以选择了

        container.add(checkBox01,BorderLayout.NORTH);
        container.add(checkBox02,BorderLayout.SOUTH);
        
        this.setVisible(true);
        this.setBounds(100,100,500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


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

    }
}

列表

下拉框

public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01(){

        Container container = this.getContentPane();


        //下拉框
        JComboBox status = new JComboBox();

        status.addItem(null);
        status.addItem("正在上映");
        status.addItem("已下架");
        status.addItem("即将上映");

        container.add(status);

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

    }

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

列表框

public class TestComboboxDemo02 extends JFrame {
    public TestComboboxDemo02(){

        Container container = this.getContentPane();

        //生成列表的内容 稀疏数组,压缩数据
        //String[] contents = {"1","2","3"};//静态

        Vector<Object> contents = new Vector();//也可以放动态的变量
        //列表中需要放入内容
        JList jList = new JList(contents);

        contents.add("张三");
        contents.add("list");
        contents.add("wangwu");
        
        container.add(jList);

        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

    }
}

文本框

文本框

public class TestTextDemo01 extends JFrame {
    public TestTextDemo01(){

        Container container = this.getContentPane();

        JTextField textField = new JTextField("hello");
        JTextField textField2 = new JTextField("world",20);

        container.add(textField,BorderLayout.NORTH);
        container.add(textField2,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

}

密码框

public class TestTextDemo02 extends JFrame {

    public TestTextDemo02(){

        Container container = this.getContentPane();

        // 面板

        JPasswordField passwordField = new JPasswordField(); // ****
        passwordField.setEchoChar('*');

        container.add(passwordField);

        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

}

文本域

public class TestTextDemo03 extends JFrame {

    public TestTextDemo03(){
        Container container = this.getContentPane();

        //文本域
        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("阿巴阿巴阿巴");

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

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

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

贪吃蛇

帧,如果时间片足够小,就是动画,一秒30帧 60帧。连起来是动画,拆开就是静态的图片!

监听监听

定时器 Timer

  1. 定义数据

  2. 画上去

  3. 监听事件

    键盘

    事件

package snake;

import javax.swing.*;

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

        frame.setBounds(10,10,900,720);
        frame.setResizable(false);//窗口大小不可变
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //正常游戏界面都应该在面上!
        frame.add(new GamePanel());
        frame.setVisible(true);

    }
}
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.Date;
import java.util.Random;

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

    //定义蛇的数据结构
    int length;
    int [] snake_x = new int[600];//x坐标
    int [] snake_y = new int[600];//y坐标
    String dir ;
    //游戏当前的状态:开始或者停止
    boolean isStart = false;//默认暂停
    boolean isFail = false;//游戏失败状态
    //食物的坐标
    int food_x;
    int food_y;
    Random random = new Random();
    int score;
    //定时器
    Timer timer = new Timer(100, this);//100ms执行一次定时器

    public GamePanel(){
        init();
        //获得焦点和键盘事件
        this.setFocusable(true);//获得焦点事件
        this.addKeyListener(this);//获得键盘监听事件
        timer.start();
    }
    //初始化
    public void init(){
        length = 3;
        snake_x[0] = 100;snake_y[0] = 100; //脑袋的坐标
        snake_x[1] = 75;snake_y[1] = 100; //第一个身体的坐标
        snake_x[2] = 50;snake_y[2] = 100; //第二个身体的坐标
        dir = "R";
        //让食物位置初始化
        food_x=25 + 25*random.nextInt(34);
        food_y=75 + 25*random.nextInt(24);
        score=0;
    }
    //绘制面板,游戏由这个画笔来画
    @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.WHITE);
        g.setFont(new Font("微软雅黑", Font.BOLD, 18));
        g.drawString("长度:"+length, 750, 35);
        g.drawString("分数:"+score, 750, 50);
        //画食物
        Data.food.paintIcon(this, g, food_x, food_y);
        //画小蛇
        if(dir.equals("R")){
            Data.right.paintIcon(this, g, snake_x[0],snake_y[0]);
        }else if(dir.equals("L")){
            Data.left.paintIcon(this, g, snake_x[0],snake_y[0]);
        }if(dir.equals("U")){
            Data.up.paintIcon(this, g, snake_x[0],snake_y[0]);
        }if(dir.equals("D")){
            Data.down.paintIcon(this, g, snake_x[0],snake_y[0]);
        }
        for(int i=1 ; i < length ; i++){
            Data.body.paintIcon(this, g, snake_x[i],snake_y[i]);
        }

        //游戏状态
        if(!isStart){
            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("游戏失败,按下空格重新开始",300,300);
        }
    }
    //键盘监听类
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode==KeyEvent.VK_SPACE){
            if (isFail){
                isFail=false;
                init();
            }else{
                isStart = !isStart;//取反
            }
            repaint();
        }
        if (keyCode==KeyEvent.VK_UP){
            dir="U";
        }else if (keyCode==KeyEvent.VK_DOWN){
            dir="D";
        }else if (keyCode==KeyEvent.VK_LEFT){
            dir="L";
        }else if (keyCode==KeyEvent.VK_RIGHT){
            dir="R";
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {
    }
    @Override
    public void keyTyped(KeyEvent e) {
    }

    //事件监听--需要
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && !isFail){
            //吃食物
            if (snake_x[0]==food_x&&snake_y[0]==food_y){
                length++;
                //再次随机食物
                score+=10;
                food_x=25 + 25*random.nextInt(34);
                food_y=75 + 25*random.nextInt(24);
            }

            //移动
            for (int i = length-1; i >0;i--){
                snake_x[i]=snake_x[i-1];//向前移动一节
                snake_y[i]=snake_y[i-1];
            }

            if(dir.equals("R")){
                snake_x[0]=snake_x[0]+25;
                if(snake_x[0]>850){ snake_x[0]=25; }
            }else if (dir.equals("L")){
                snake_x[0]=snake_x[0]-25;
                if(snake_x[0]<25){ snake_x[0]=850; }
            }else if (dir.equals("U")){
                snake_y[0]=snake_y[0]-25;
                if(snake_y[0]<75){ snake_y[0]=650; }
            }else if (dir.equals("D")){
                snake_y[0]=snake_y[0]+25;
                if(snake_y[0]>650){ snake_y[0]=75; }
            }

            repaint();
        }
        //失败判断
        for (int i=1;i<length;i++){
            if (snake_x[0]==snake_x[i] && snake_y[0]==snake_y[i]){
                isFail=true;
            }
        }

        timer.start();//定时器开始
    }
}

package snake;

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

//写一个数据中心
public class Data {

    //相对路径
    //绝对路径
    public static URL headerURL = Data.class.getResource("/statics/header.png");
    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 = 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-06-13 01:46  doms-xiang  阅读(48)  评论(0)    收藏  举报