GUI编程入门与贪吃蛇(自用)

GUI编程

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

1.简介

2.AWT

2.1AWT介绍

1. 包含了很多类和接口
  1. 元素:窗口丶按钮丶文本框
  2. java.awt

在这里插入图片描述

2.2 Frame

package gui_study;

import java.awt.Color;
import java.awt.Frame;

public class Demo {
    
    

	public static void main(String[] args) {
    
    
//		Frame frame = new Frame("我的第一个java图像界面窗口");
//
//		// 设置可见性
//		frame.setVisible(true);
//
//		// 设置窗口大小
//		frame.setSize(400, 400);
//
//		// 设置背景颜色
//		frame.setBackground(new Color(1, 1, 1));
//
//		// 弹出的初始位置
//		frame.setLocation(200, 200);
//
//		// 设置大小固定
//		frame.setResizable(false);
		MyFrame myFrame1 = new MyFrame(100,100,200,200,Color.blue);
		MyFrame myFrame2 = new MyFrame(300,100,200,200,Color.BLACK);
		MyFrame myFrame3 = new MyFrame(100,300,200,200,Color.green);
		MyFrame myFrame4 = new MyFrame(300,300,200,200,Color.yellow);

	}

}

//实现创建多个窗口
class MyFrame extends Frame {
    
    
	static int a = 0;

	public MyFrame(int x, int y, int w, int h, Color color) {
    
    
		super("id" + (++a));
		setBackground(color);
//设置 坐标和宽高
		setBounds(x, y, w, h);
		setVisible(true);
	}
}

2.3 面板Panel

package gui_study;

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

//paneL 可以看成是一个空间,但是不能单独存在
public class Demo {
    
    

	public static void main(String[] args) {
    
    
		Frame frame = new Frame();
		Panel panel = new Panel();

//		设置布局
		frame.setLayout(null);

		frame.setBounds(300, 300, 500, 500);
		frame.setBackground(Color.red);

//		设置paneL坐标,相对于frame
		panel.setBounds(50, 50, 400, 400);
		panel.setBackground(Color.blue);
//		添加到主面板
		frame.add(panel);
//		设置可见
		frame.setVisible(true);
//		监听事件,监听窗口关闭事件
//		适配器模式:
		frame.addWindowListener(new WindowAdapter() {
    
    
//			窗口点击关闭的时候需要做的事情
			public void windowClosing(WindowEvent e) {
    
    
//				结束程序
				System.exit(0);
			}
		});
	}
}

2.4布局管理器

  • 流式布局
package gui_study;

import java.awt.*;

public class Demo {
    
    

	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.setSize(300, 300);
		frame.setVisible(true);

		frame.add(button1);
		frame.add(button2);
		frame.add(button3);

//		设置为流式布局
//		居中
		frame.setLayout(new FlowLayout());
//		从左到右
		frame.setLayout(new FlowLayout(FlowLayout.LEFT));

	}
}

  • 东西南北中
package gui_study;

import java.awt.*;

public class Demo {
    
    

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

//		组件-布局
		Button east = new Button("east");
		Button west = new Button("west");
		Button south = new Button("south");
		Button north = new Button("north");
		Button center = new Button("center");

		frame.setSize(300, 300);
		frame.setVisible(true);

		frame.add(east, BorderLayout.EAST);
		frame.add(west, BorderLayout.WEST);
		frame.add(south, BorderLayout.SOUTH);
		frame.add(north, BorderLayout.NORTH);
		frame.add(center, BorderLayout.CENTER);

	}
}

  • 表格布局
package gui_study;

import java.awt.*;

public class Demo {
    
    

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

//		组件-布局
		Button btn1 = new Button("east");
		Button btn2 = new Button("west");
		Button btn3 = new Button("south");
		Button btn4 = new Button("north");
		Button btn5 = new Button("center");
		Button btn6 = new Button("center");

		frame.setSize(600, 600);
		frame.setVisible(true);

		frame.add(btn1);
		frame.add(btn2);
		frame.add(btn3);
		frame.add(btn4);
		frame.add(btn5);
		frame.add(btn6);

//		java函数,实现自动布局优化
		frame.pack();
//		实现三行两列的表格布局
		frame.setLayout(new GridLayout(3, 2));

	}
}

2.5 事件监听

package gui_study;

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

public class Demo {
    
    

	public static void main(String[] args) {
    
    
		Frame frame = new Frame();
		Button button1 = new Button("but1");
		Button button2 = new Button("but2");
		
//		可以显示定义触发返回的命令,如果不定义,则返回默认值
//		可以多个按钮只写一个监听类
		button1.setActionCommand("stop");
		myMonitor monitor = new myMonitor();
		button1.addActionListener(monitor);
		button2.addActionListener(monitor);
		
		frame.add(button1,BorderLayout.NORTH);
		frame.add(button2,BorderLayout.SOUTH);
		frame.setSize(300,300);
		frame.pack();
		frame.setVisible(true);
	}

}
class myMonitor implements ActionListener{
    
    

	@Override
	public void actionPerformed(ActionEvent e) {
    
    
//		e.getActionCommand() 获取按钮信息
		System.out.println("按钮被点击了"+e.getActionCommand());
		
	}
	
}

2.6输入框事件监听

package gui_study;

import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Demo {
    
    

	public static void main(String[] args) {
    
    
	new MyFrame();
	
	}
	
}
class MyFrame extends Frame{
    
    
	public MyFrame(){
    
    
		TextField textField = new TextField();
		add(textField);
//		监听这个文本框输入的文字
		MyActionListener myActionListener = new MyActionListener();
//		按下回车,就会触发这个输入框的事件
		textField.addActionListener(myActionListener);
		
//		设置替换编码
		textField.setEchoChar('*');
		setVisible(true);
		pack();
		setSize(300,200);
	}
}

class MyActionListener implements ActionListener{
    
    

	@Override
	public void actionPerformed(ActionEvent e) {
    
    
		TextField textField=(TextField)e.getSource();//获得一些资源,返回一个超类
		System.out.println(textField.getText());//
		textField.setText("");//回车输入框为空
	}
	
}

2.7 简易计算器

package gui_study;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Demo {
    
    

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

class Calulator extends Frame {
    
    
	public Calulator() {
    
    
//	三个文本框
		TextField num1 = new TextField(10);// 字符数为10
		TextField num2 = new TextField(10);
		TextField num3 = new TextField(20);

//	一个按钮
		Button button = new Button("=");

//	一个标签
		Label lbLabel = new Label("+");

		setLayout(new FlowLayout());
		add(num1);
		add(lbLabel);
		add(num2);
		add(button);
		add(num3);

		setVisible(true);
		pack();

		button.addActionListener(new MycalculatorListener(num1,num2,num3));
	}
}

class MycalculatorListener implements ActionListener{
    
    

	private TextField num1,num2,num3;
	public	MycalculatorListener(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.setText("");
		num2.setText("");
		
		
	}
	
}

代码优化:实现面向对象

package gui_study;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Demo {
    
    

	public static void main(String[] args) {
    
    
		new Calulator().laodFrame();
	}
}

class Calulator extends Frame {
    
    
	TextField num1, num2, num3;

	public void laodFrame() {
    
    

//	三个文本框
		num1 = new TextField(10);// 字符数为10
		num2 = new TextField(10);
		num3 = new TextField(20);

//	一个按钮
		Button button = new Button("=");

//	一个标签
		Label lbLabel = new Label("+");

		setLayout(new FlowLayout());
		add(num1);
		add(lbLabel);
		add(num2);
		add(button);
		add(num3);

		setVisible(true);
		pack();
		button.addActionListener(new MycalculatorListener());
	}
//内部类完成监听
	private class MycalculatorListener implements ActionListener {
    
    

		@Override
		public void actionPerformed(ActionEvent e) {
    
    
			int n1 = Integer.parseInt(num1.getText());
			int n2 = Integer.parseInt(num2.getText());

			num3.setText("" + (n1 + n2));
			num1.setText("");
			num2.setText("");

		}

	}
}

2.8 画板paint

package gui_study;

import java.awt.*;

public class Demo {
    
    

	public static void main(String[] args) {
    
    
		new MyPanit().loadFrame();;
	}
}
class MyPanit extends Frame{
    
    
	public void loadFrame() {
    
    
//		设置画板坐标,大小
		setBounds(200, 200, 600, 500);
		setVisible(true);
	}
	
	public void paint(Graphics graphics) {
    
    
//		画出图形颜色
		graphics.setColor(Color.red);
//		设置空心圆坐标,大小
		graphics.drawOval(100, 100, 100, 100);
//		设置实心圆坐标,大小
		graphics.fillOval(200, 200, 100, 100);
		
	}
}

2.9 鼠标监听事件:模拟画图工具

package gui_study;

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

public class Demo {
    
    

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

class MyFrame extends Frame {
    
    
	ArrayList points;

	public MyFrame(String title) {
    
    
		super("title");
		setBounds(200, 200, 400, 300);
		points = new ArrayList<>();
		setVisible(true);

		this.addMouseListener(new MyMouseListener());
	}

	public void paint(Graphics graphics) {
    
    
		// 画点
//		迭代集合中的点
		Iterator iterator = points.iterator();
		while (iterator.hasNext()) {
    
    
			Point point = (Point) iterator.next();
			graphics.setColor(Color.green);
			graphics.fillOval(point.x, point.y, 10, 10);
		}
	}

//	添加一个点到界面上
	public void addPaint(Point point) {
    
    
		points.add(point);
	}

	private class MyMouseListener extends MouseAdapter {
    
    
		@Override
		//按下鼠标时调用
		public void mousePressed(MouseEvent e) {
    
    
			MyFrame myFrame = (MyFrame) e.getSource();
			myFrame.addPaint(new Point(e.getX(), e.getY()));
			//刷新窗口
			myFrame.repaint();
		}

	}
}

2.10 窗口监听事件

package gui_study;

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

public class Demo {
    
    

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

}

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

		this.addWindowListener(new WindowListener() {
    
    

			// 关闭窗口
			@Override
			public void windowClosing(WindowEvent e) {
    
    
				System.out.println("关闭窗口");
				System.exit(0);
			}

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

	}

}

2.11键盘监听事件

package gui_study;

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


public class Demo {
    
    

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

}

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

		this.addKeyListener(new KeyAdapter() {
    
    
			//键盘按下事件
			@Override
			public void keyReleased(KeyEvent e) {
    
    
//				getKeyCode 获得当前按下键的码
				int gKC=e.getKeyCode();
				if (gKC==KeyEvent.VK_UP) {
    
    
					System.out.println("你按下了上键");
				}
			}
		});
		 

	}

}

3. Swing

3.1 窗口丶面板

package gui_study;

import java.awt.*;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

public class Demo {
    
    
//	init() 初始化
	public void init() {
    
    
		JFrame jFrame = new JFrame("这是一个jFrame窗口");
		jFrame.setVisible(true);
		jFrame.setBounds(100, 200, 200, 200);
		jFrame.setBackground(Color.black);
		
		JLabel jLabel = new JLabel("这是一段文本");
		
		jFrame.add(jLabel);
		
//		关闭事件
		jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args) {
    
    
//		建立一个窗口
		new Demo().init();
	}
}



3.2 JFrame弹窗

package gui_study;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public void DialogDeme() {
    
    
		this.setVisible(true);
		this.setSize(700, 500);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		// Jframe不能直接添加组件,用getContentPane获取面板,再添加
		Container container = this.getContentPane();

		container.setLayout(null);

		JButton button = new JButton("点击弹出一个弹窗");
		button.setBounds(30, 30, 200, 500);

		button.addActionListener(new ActionListener() {
    
    

			@Override
			public void actionPerformed(ActionEvent e) {
    
    
				new MyDialogDemo();
			}
		});
		container.add(button);

	}

	public static void main(String[] args) {
    
    
		new Demo().DialogDeme();
	}

	class MyDialogDemo extends JDialog {
    
    
		public MyDialogDemo() {
    
    
			this.setVisible(true);
			this.setBounds(100, 100, 500, 500);
//			JDialog自带关闭事件,不需要写
//			this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);;

//			添加文本操作
			Container container = this.getContentPane();
			container.setLayout(null);
			container.add(new Label("这是一段文本"));
		}
	}
}

3.3 icon丶imagelcon标签

icon

package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    

		JLabel jLabel = new JLabel("ImageIcon");
//		获取图片地址
		URL url=Demo.class.getResource("001.png");

		ImageIcon imageIcon = new ImageIcon(url);
		jLabel.setIcon(imageIcon);
		jLabel.setHorizontalAlignment(SwingConstants.CENTER);

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

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

	}

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

3.4 文本域和JScroll面板

package gui;

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

import javax.swing.*;

import study.Dome;
import test.jsq;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
//		文本域
		JTextArea textArea = new JTextArea(20, 20);
		textArea.setText("这是一段文本");
//		Scroll面板(有滑动条的面板)		
		JScrollPane scrollPane = new JScrollPane(textArea);
		container.add(scrollPane);
		this.setVisible(true);
		this.setSize(500, 500);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

	}

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

补充:面板布局

package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

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

//	10,10是设置面板之间的间距
		container.setLayout(new GridLayout(2, 1, 10, 10));
		JPanel jPanel = new JPanel(new GridLayout(1, 2));
		JPanel jPanel2 = new JPanel(new GridLayout(2, 2));
		JPanel jPanel3 = new JPanel(new GridLayout(1, 1));

		jPanel.add(new JButton("1"));
		jPanel.add(new JButton("2"));
		jPanel.add(new JButton("3"));

		jPanel2.add(new JButton("3"));
		jPanel2.add(new JButton("3"));
		jPanel2.add(new JButton("3"));
		jPanel2.add(new JButton("3"));
		jPanel3.add(new JButton("3"));

		container.add(jPanel);
		container.add(jPanel2);
		container.add(jPanel3);

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

	}

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

3.5 按钮

  • 图片按钮:
package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
//		获得图片地址
		URL url = Demo.class.getResource("001.png");
//		获得图片
		Icon icon = new ImageIcon(url);

		JButton jButton = new JButton();
		jButton.setIcon(icon);
		jButton.setToolTipText("图片按钮");

		container.add(jButton);

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

	}

	public static void main(String[] args) {
    
    
		new Demo();
	}
}
  • 单选框:
package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
		JRadioButton radioButton1 = new JRadioButton("1");
		JRadioButton radioButton2 = new JRadioButton("2");
		JRadioButton radioButton3 = new JRadioButton("3");

		ButtonGroup buttonGroup = new ButtonGroup();
		buttonGroup.add(radioButton1);
		buttonGroup.add(radioButton2);
		buttonGroup.add(radioButton3);

		container.add(radioButton1, BorderLayout.CENTER);
		container.add(radioButton2, BorderLayout.NORTH);
		container.add(radioButton3, BorderLayout.SOUTH);
		this.setVisible(true);
		this.setSize(500, 500);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

	}

	public static void main(String[] args) {
    
    
		new Demo();
	}
}
  • 多选框
package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
		JCheckBox checkBox1 = new JCheckBox("1");
		JCheckBox checkBox2 = new JCheckBox("2");
		JCheckBox checkBox3 = new JCheckBox("3");

		container.add(checkBox1, BorderLayout.CENTER);
		container.add(checkBox2, BorderLayout.NORTH);
		container.add(checkBox3, BorderLayout.SOUTH);
		this.setVisible(true);
		this.setSize(500, 500);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

	}

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

3.6 下拉框丶多选框

  • 下拉框:
package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
		JComboBox jComboBox = new JComboBox();
		jComboBox.addItem(null);
		jComboBox.addItem("正在热映");
		jComboBox.addItem("已下架");
		jComboBox.addItem("即将上映");

		container.add(jComboBox);

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

	}

	public static void main(String[] args) {
    
    
		new Demo();
	}
}
  • 列表框
package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
//		String[] str = { "1", "2", "3", "4" };静态引用
//		JList jList = new JList(str);
//		container.add(jList);

		Vector vector = new Vector();
		JList jList = new JList(vector);
		//动态引用
		vector.add("1");
		vector.add("2");

		container.add(jList);

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

	}

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

3.7 文本框丶密码框

package gui;

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

import javax.swing.*;

import study.Dome;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
		container.setLayout(null);
		JTextField jTextField = new JTextField("hello");
		JTextField jTextField2 = new JTextField("world");

		container.add(jTextField, BorderLayout.NORTH);
		container.add(jTextField2, BorderLayout.SOUTH);

		this.setVisible(true);
		this.setSize(520, 300);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

	}

	public static void main(String[] args) {
    
    
		new Demo();
	}
}
  • 密码框
package gui;

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

import javax.swing.*;

import study.Dome;
import test.jsq;

public class Demo extends JFrame {
    
    

	public Demo() {
    
    
		Container container = this.getContentPane();
		JPasswordField jPasswordField = new JPasswordField();
		jPasswordField.setEchoChar('*');
		container.add(jPasswordField);

		this.setVisible(true);
		this.setSize(520, 300);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

	}

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

4.贪吃蛇

package snake;
//数据中心

import java.net.URL;

import javax.swing.ImageIcon;

public class Data {
    
    

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

	public static ImageIcon body = new ImageIcon(bodyURL);
	public static ImageIcon down = new ImageIcon(downURL);
	public static ImageIcon food = new ImageIcon(foodURL);
	public static ImageIcon header = new ImageIcon(headerURL);
	public static ImageIcon left = new ImageIcon(leftURL);
	public static ImageIcon right = new ImageIcon(rightURL);
	public static ImageIcon up = new ImageIcon(upURL);
}

package snake;

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

import javax.swing.*;

public class Gamepanel extends JPanel implements KeyListener, ActionListener {
    
    
	int length;// 蛇的长度
	int[] snakeX = new int[600];// 蛇的x坐标25*25
	int[] snakeY = new int[500];// 蛇的y坐标25*25
	String fx;// 方向
	// 游戏当前的状态
	boolean isStart;
	boolean isFail = false;// 游戏失败状态
	int foodX;
	int foodY;
	Random random = new Random();
	
	int score;

	// 定时器 以ms为单位,1000ms=1s
	Timer timer = new Timer(100, this);// 100毫秒执行一次

	public Gamepanel() {
    
    
		init();
//		获得焦点和键盘事件
		this.setFocusable(true);// 获得焦点事件
		this.addKeyListener(this);// 获得键盘监听事件
		timer.start();
	}

	public void init() {
    
    
		length = 3;
		snakeX[0] = 100;
		snakeY[0] = 100;// 蛇头的坐标
		snakeX[1] = 75;
		snakeY[1] = 100;// 第一节身体的坐标
		snakeX[2] = 50;
		snakeY[2] = 100;// 第二节的身体的坐标
		fx = "R";
		isStart = false;
//		把食物随机分布在界面上
		foodX = 25 + 25 * random.nextInt(34);
		foodY = 75 + 25 * random.nextInt(24);
		score=0;
	}

	// 使用Graphics绘制面板
	// 注意重写的方法paintComponents------
	@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, 55);
		
		// 画食物
		Data.food.paintIcon(this, g, foodX, foodY);
		// 根据方向画蛇头
		if (fx.equals("R")) {
    
    
			Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);
		} else if (fx.equals("L")) {
    
    
			Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);
		} else if (fx.equals("U")) {
    
    
			Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);
		} else if (fx.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 (isStart == false) {
    
    
			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 keyTyped(KeyEvent e) {
    
    
	}

//按下事件
	@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) {
    
    
			fx = "U";
		} else if (keyCode == KeyEvent.VK_DOWN) {
    
    
			fx = "D";
		} else if (keyCode == KeyEvent.VK_LEFT) {
    
    
			fx = "L";
		} else if (keyCode == KeyEvent.VK_RIGHT) {
    
    
			fx = "R";
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
    
    
	}

	// 事件监听---需要通过固定事件来刷新,1s=10次
	@Override
	public void actionPerformed(ActionEvent e) {
    
    
		if (isStart && isFail == false) {
    
    
			//吃食物
			if (snakeX[0] == foodX && snakeY[0] == foodY) {
    
    
				length++;
				//分数加10
				score+=10;
				// 再次随机食物
				foodX = 25 + 25 * random.nextInt(34);
				foodY = 75 + 25 * random.nextInt(24);
			}
			// 身体移动
			for (int i = length - 1; i > 0; i--) {
    
    
				snakeX[i] = snakeX[i - 1];
				snakeY[i] = snakeY[i - 1];
			}

			// 走向
			if (fx.equals("R")) {
    
    
				snakeX[0] = snakeX[0] + 25;
				// 边界判断
				if (snakeX[0] > 850) {
    
    
					snakeX[0] = 25;
				}
			} else if (fx.equals("L")) {
    
    
				snakeX[0] = snakeX[0] - 25;
				// 边界判断
				if (snakeX[0] < 25) {
    
    
					snakeX[0] = 850;
				}
			} else if (fx.equals("U")) {
    
    
				snakeY[0] = snakeY[0] - 25;
				// 边界判断
				if (snakeY[0] < 75) {
    
    
					snakeY[0] = 650;
				}
			} else if (fx.equals("D")) {
    
    
				snakeY[0] = snakeY[0] + 25;
				// 边界判断
				if (snakeY[0] > 650) {
    
    
					snakeY[0] = 75;
				}
			}
			for (int i = 1; i < length; i++) {
    
    
				if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
    
    
					isFail = true;
				}
			}
			repaint();
		}
		timer.start();// 定时器开启
	}

}

package snake;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

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);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_34509897/article/details/116679998