GUI编程
组件:
窗口
弹窗
面板
文本框
列表框
按钮
图片
监听事件
鼠标事件
键盘事件
1.简介
Gui的核心技术:Swing AWT
1.界面不美观.
2.需要jre环境
为什么要学习
1.写出小工具
2.维护swing界面
3.了解MVC架构,了解监听
2.AWT
2.1AWT介绍
包含了很多类和接口!GUI!
元素:窗口,按钮,文本框
java.awt

2.2组件和容器
1.Frame
//GUI第一个界面
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(203, 60, 60));
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
//设置窗口关闭
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
尝试回顾封装
public class TestFrame2 {
public static void main(String[] args) {
//展示多个窗口
MyFrame myFrame1 = new MyFrame(100,100,100,100,new Color(152, 43, 43));
MyFrame myFrame2 = new MyFrame(200,100,100,100,new Color(79, 43, 152));
MyFrame myFrame3 = new MyFrame(100,200,100,100,new Color(224, 18, 127));
MyFrame myFrame4 = new MyFrame(200,200,100,100,new Color(63, 152, 43));
}
}
class MyFrame extends Frame{
static int count = 0;
public MyFrame(int x , int y,int w, int h,Color color){
super("myFrane" + (++count));
setBounds(x,y,w,h);
setBackground(color);
setVisible(true);
}
}
2.面板Panel
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame();
//布局概念
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//坐标
frame.setBounds(200,200,200,200);
frame.setBackground(new Color(188, 21, 206));
//panel设置坐标
panel.setBounds(100,100,100,100);
panel.setBackground(Color.blue);
//frame.add
frame.add(panel);
frame.setVisible(true);
//监听事件,监听窗口关闭 system.exit(0);
//适配器模式:
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
3.布局管理器
- 流式布局
- 东西南北中
- 表格布局
- 流式布局
public class TestFlowLayout {
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.CENTER));
// frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
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);
}
});
}
}
- 东西南北中
public class TestBorderLayout {
public static void main(String[] args) {
Frame frame = new Frame();
Button east = new Button("East");
Button center = new Button("Center");
Button west = new Button("West");
Button south = new Button("South");
Button north = new Button("North");
frame.add(east,BorderLayout.EAST);
frame.add(center,BorderLayout.CENTER);
frame.add(west,BorderLayout.WEST);
frame.add(south,BorderLayout.SOUTH);
frame.add(north,BorderLayout.NORTH);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
- 表格布局
public class TestGridLayout {
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 GridLayout(3,0));
frame.setBounds(100,100,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);
}
});
}
}
4.事件监听
事件监听
按钮
//监听事件
public class TestAction {
public static void main(String[] args) {
//按下按钮触发事件
Frame frame = new Frame();
frame.setBounds(500,500,500,500);
Button button = new Button("button");
//因为,addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
button.addActionListener(new MyActionListener());
frame.add(button,BorderLayout.CENTER);
frame.setVisible(true);
WindowColse(frame);
}
//关闭方法
public static void WindowColse(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("button");
}
}
多个按钮共享一个事件
public class TestAction02 {
public static void main(String[] args) {
//两个按钮 实现一个监听
//开始 停止
Frame frame = new Frame("开始-停止");
frame.setBounds(500,500,500,500);
Button button1 = new Button("start");
Button button2 = new Button("stop");
button1.setActionCommand("start");
button2.setActionCommand("stop");
frame.setVisible(true);
new WindowClose(frame);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack();
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击:" + e.getActionCommand());
}
}
5.输入框
输入文本框监听
public class TestText01 {
public static void main(String[] args) {
//启动
MyFrame myFrame = new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame() throws HeadlessException {
TextField textField = new TextField();
add(textField);
//监听这个文本框输入的文字
MyActionListener2 myActionListener2 = new MyActionListener2();
//按下回车触发监听
textField.addActionListener(myActionListener2);
//设置编码
textField.setEchoChar('*');
setVisible(true);
pack();
new WindowClose(this);
}
}
class MyActionListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField textField = (TextField) e.getSource();//获得资源
System.out.println(textField.getText());//获得输入的文本
textField.setText("");
}
}
6.简易计算器,组合+内部类
oop原则:组合,大于继承
//简易计算器
public class TestCalc {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.loadFrame();
}
}
/**
* 计算器类
*/
class Calculator extends Frame{
/**
* 属性
*/
TextField textField1;
TextField textField2;
TextField textField3;
/**
* 方法
*/
public void loadFrame() {
//3个文本框
//10为字符数
textField1 = new TextField(10);
textField2 = new TextField(10);
textField3 = new TextField(10);
//一个按钮
Button button = new Button("=");
button.addActionListener(new MyActionListener3(this));
//一个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(textField1);
add(label);
add(textField2);
add(button);
add(textField3);
setVisible(true);
pack();
new WindowClose(this);
}
}
class MyActionListener3 implements ActionListener {
/**
*获取计算器这个对象,在一个类中组合另一个类
*/
Calculator calculator;
public MyActionListener3(Calculator calculator) {
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
//1.获得加数和被加数
int num1 =Integer.parseInt(calculator.textField1.getText());
int num2 =Integer.parseInt(calculator.textField2.getText());
int num3;
//2.将这个值+法运算后,放到第三个框
num3 = num1 + num2;
calculator.textField3.setText(""+num3);
//3.清除前两个框
calculator.textField1.setText("");
calculator.textField2.setText("");
}
}
改造为面向对象
- 内部类
//简易计算器
public class TestCalc {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.loadFrame();
}
}
/**
* 计算器类
*/
class Calculator extends Frame{
/**
* 属性
*/
TextField textField1;
TextField textField2;
TextField textField3;
/**
* 方法
*/
public void loadFrame() {
//3个文本框
//10为字符数
textField1 = new TextField(10);
textField2 = new TextField(10);
textField3 = new TextField(10);
//一个按钮
Button button = new Button("=");
button.addActionListener(new MyActionListener3());
//一个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(textField1);
add(label);
add(textField2);
add(button);
add(textField3);
setVisible(true);
pack();
new WindowClose(this);
}
/**
* 监听器
* 内部类可以畅通使用外部类的属性和方法
*/
private class MyActionListener3 implements ActionListener {
/**
*获取计算器这个对象,在一个类中组合另一个类
*/
@Override
public void actionPerformed(ActionEvent e) {
//1.获得加数和被加数
int num1 =Integer.parseInt(textField1.getText());
int num2 =Integer.parseInt(textField2.getText());
int num3;
//2.将这个值+法运算后,放到第三个框
num3 = num1 + num2;
textField3.setText(""+num3);
//3.清除前两个框
textField1.setText("");
textField2.setText("");
}
}
}
7.画笔
public class TestPaint01 {
public static void main(String[] args) {
new Mypaint().loadFrame();
}
}
class Mypaint extends Frame{
public void loadFrame(){
setBounds(500,500,500,500);
setVisible(true);
new WindowClose(this);
}
//画笔
@Override
public void paint(Graphics g) {
//画笔,颜色
g.setColor(Color.blue);
g.drawRoundRect(100,100,100,100,0,0);
g.setColor(Color.CYAN);
g.drawOval(200,200,100,100);
g.setColor(Color.green);
g.fillOval(400,100,100,100);
//画笔用完,将他还原到最初的颜色
g.setColor(Color.BLACK);
}
}
8.鼠标监听
目的:实现鼠标画画!
public class TestMouseListener {
public static void main(String[] args) {
new MyFrame("画画");
}
}
class MyFrame extends Frame {
//画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
ArrayList points;
public MyFrame(String title) {
super(title);
setBounds(500,500,500,500);
//存鼠标点击的点
points = new ArrayList();
//鼠标监听器,针对这个窗口
this.addMouseListener(new MyMouseListener());
setVisible(true);
new WindowClose(this);
}
@Override
public void paint(Graphics g) {
//画画监听鼠标事件
Iterator iterator = points.iterator();
while(iterator.hasNext()){
Point point = (Point) iterator.next();
g.setColor(Color.blue);
g.fillOval(point.x,point.y,10,10);
}
}
//添加一个点到界面上
public void addPoint(Point point){
points.add(point);
}
//适配器模式
private class MyMouseListener extends MouseAdapter {
//鼠标 按下,弹起,按住不放
@Override
public void mousePressed(MouseEvent e) {
MyFrame frame = (MyFrame) e.getSource();
//点击,在界面上产生一个点
//这点就是鼠标的点
frame.addPoint(new Point(e.getX(),e.getY()));
//每次点此鼠标,需要重画一次
repaint();
}
}
}

9.窗口监听
public class TestWindowListener {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame {
public WindowFrame(){
setBackground(Color.red);
setBounds(500,500,500,500);
setVisible(true);
//addWindowListener(new MyWindowListener());
addWindowListener(
//匿名内部类
new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened");
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("windowclosed");
}
//激活窗口
@Override
public void windowActivated(WindowEvent e) {
System.out.println("windowactived");
}
//关闭窗口
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowclosed");
System.exit(0);
}
});
}
}
10.键盘监听
//键盘监听
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame() {
setBounds(500,500,500,500);
setVisible(true);
addKeyListener(new KeyAdapter() {
//键盘按下
@Override
public void keyPressed(KeyEvent e) {
//获得键盘按下的键,当前键盘的码
//不需要记住keycode ,直接使用静态属性 VK_XX
int keycode = e.getKeyCode();
char keychar = e.getKeyChar();
System.out.println("你按下了" + keychar + "对应数字为" + keycode);
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
3.Swing
1.窗口、面板
在容器上的container
public class JFrameDemo01 {
//init();初始化
public void init(){
//顶级窗口
JFrame jf = new JFrame("JFrame窗口");
jf.setVisible(true);
jf.setBounds(500,500,500,500);
//设置文字 label
JLabel jl = new JLabel("java");
jf.add(jl);
//容器
Container contentPane = jf.getContentPane();
contentPane.setBackground(Color.CYAN);
//关闭事件
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//建立窗口
new JFrameDemo01().init();
}
}
标签居中
public class JFrameDemo02 {
public static void main(String[] args) {
new MyJFrame().init();
}
}
class MyJFrame extends JFrame{
public void init(){
setVisible(true);
setBounds(500,500,500,500);
//设置文字 label
JLabel jl = new JLabel("java");
add(jl);
//让文本标签居中
jl.setHorizontalAlignment(SwingConstants.CENTER);
//获得容器
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.CYAN);
}
}
2.弹窗
JDialog,用来弹出事件,默认就有关闭
//主窗口
public class DialogDemo extends JFrame {
public DialogDemo(){
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame 放东西 ,容器
Container container = this.getContentPane();
//绝对布局
container.setLayout(null);
//按钮
JButton button = new JButton("点击弹出对话框");
button.setBounds(100,100,150,150);
//点击按钮弹出弹窗
container.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//弹窗
new MyDialog();
}
});
}
public static void main(String[] args) {
new DialogDemo();
}
}
//弹窗的窗口
class MyDialog extends JDialog{
public MyDialog() {
this.setVisible(true);
this.setBounds(100,100,100,100);
Container container =this.getContentPane();
container.setLayout(null);
container.add(new Label("java"));
}
}
3.标签
label
new Jlabel("");
图标 ICON
//ICON,需要实现类,Frame继承
public class IconDemo extends JFrame implements Icon {
private int width;
private int heigth;
public IconDemo(){}
public IconDemo(int width, int heigth){
this.width = width;
this.heigth = heigth;
}
public void init(){
IconDemo iconDemo = new IconDemo(15, 15);
//图标放在标签,也可以放在按钮上!
JLabel jLabel = new JLabel("icontest",iconDemo,SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(jLabel);
this.setVisible(true);
this.setBounds(100,100,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fillOval(x,y,width,heigth);
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.heigth;
}
public static void main(String[] args) {
new IconDemo().init();
}
}
图片ICON
public class ImageIconDemo extends JFrame{
public ImageIconDemo(){
JLabel jLabel = new JLabel("图片");
//获取图片地址
URL url = ImageIconDemo.class.getResource("5.jpg");
ImageIcon imageIcon = new ImageIcon(url);
jLabel.setIcon(imageIcon);
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(jLabel);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}
4.面板
JPanel
public class JpanelDemo extends JFrame {
public JpanelDemo(){
Container contentPane =this.getContentPane();
contentPane.setLayout(new GridLayout(2,1,10,10));//后面的参数为面板间距
JPanel jPanel1 = new JPanel(new GridLayout(1,3));
JPanel jPanel2 = new JPanel(new GridLayout(1,2));
JPanel jPanel3 = new JPanel(new GridLayout(2,1));
JPanel jPanel4 = new JPanel(new GridLayout(3,2));
jPanel1.add(new Button("1"));
jPanel1.add(new Button("1"));
jPanel1.add(new Button("1"));
jPanel2.add(new Button("1"));
jPanel2.add(new Button("1"));
jPanel3.add(new Button("1"));
jPanel3.add(new Button("1"));
jPanel4.add(new Button("1"));
jPanel4.add(new Button("1"));
jPanel4.add(new Button("1"));
jPanel4.add(new Button("1"));
jPanel4.add(new Button("1"));
jPanel4.add(new Button("1"));
contentPane.add(jPanel1);
contentPane.add(jPanel2);
contentPane.add(jPanel3);
contentPane.add(jPanel4);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(500,500);
}
public static void main(String[] args) {
new JpanelDemo();
}
}
JScrollPanel
public class JScrollDemo extends JFrame {
public JScrollDemo(){
Container contentPane = this.getContentPane();
//文本域
JTextArea jTextArea = new JTextArea(20,40);
jTextArea.setText("请输入文本!");
//scroll面板
JScrollPane jScrollPane = new JScrollPane(jTextArea);
contentPane.add(jScrollPane);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,100,100);
this.setVisible(true);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
5.按钮
- 图片按钮
public class JButtonDemo extends JFrame {
public JButtonDemo(){
Container contentPane = this.getContentPane();
//图片变为图标
URL url = JButtonDemo.class.getResource("下载.png");
Icon icon = new ImageIcon(url);
//图标放在按钮上
JButton jButton = new JButton();
jButton.setIcon(icon);
jButton.setText("半页");
jButton.setToolTipText("点击按钮");
contentPane.add(jButton);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
- 单选按钮
public class JButtonDemo02 extends JFrame{
public JButtonDemo02(){
Container contentPane = this.getContentPane();
//图片变为图标
URL url = JButtonDemo.class.getResource("下载.png");
Icon icon = new ImageIcon(url);
//单选框
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);
contentPane.add(jRadioButton1,BorderLayout.CENTER);
contentPane.add(jRadioButton2,BorderLayout.NORTH);
contentPane.add(jRadioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
- 复选按钮
public class JButtonDemo03 extends JFrame{
public JButtonDemo03(){
Container contentPane = this.getContentPane();
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER));
//图片变为图标
URL url = JButtonDemo.class.getResource("下载.png");
Icon icon = new ImageIcon(url);
//多选框
Checkbox checkbox1 = new Checkbox("checkbox1");
Checkbox checkbox2 = new Checkbox("checkbox2");
Checkbox checkbox3 = new Checkbox("checkbox3");
contentPane.add(checkbox1);
contentPane.add(checkbox2);
contentPane.add(checkbox3);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
6.列表
- 下拉框
public class TestComboboxDemo01 extends JFrame {
public TestComboboxDemo01(){
Container contentPane = this.getContentPane();
JComboBox jComboBox = new JComboBox();
jComboBox.addItem(null);
jComboBox.addItem("1");
jComboBox.addItem("2");
jComboBox.addItem("3");
contentPane.add(jComboBox);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo01();
}
}
- 列表框
public class TestComboboxDemo02 extends JFrame {
public TestComboboxDemo02(){
Container contentPane = this.getContentPane();
//生成列表内容
//String[] contents = {"1","2","3"};
Vector contents = new Vector();
//列表中放入内容
JList List = new JList(contents);
contents.add("1");
contents.add("2");
contents.add("3");
contentPane.add(List);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo02();
}
}
应用场景
- 选择地区,或一些单个选项
- 列表展示信息,一般是动态扩容
7.文本框
- 文本框
public class TestTextDemo01 extends JFrame {
public TestTextDemo01(){
Container contentPane = this.getContentPane();
JTextField jTextField = new JTextField("hello");
JTextField jTextField2 = new JTextField("world",20);
contentPane.add(jTextField,BorderLayout.NORTH);
contentPane.add(jTextField2,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo01();
}
}
- 密码框
public class TestTextDemo02 extends JFrame {
public TestTextDemo02(){
Container contentPane = this.getContentPane();
//密码框
JPasswordField jPasswordField = new JPasswordField();
jPasswordField.setEchoChar('*');
contentPane.add(jPasswordField);
this.setVisible(true);
this.setBounds(500,500,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo02();
}
}
- 文本域
public class JScrollDemo extends JFrame {
public JScrollDemo(){
Container contentPane = this.getContentPane();
//文本域
JTextArea jTextArea = new JTextArea(20,40);
jTextArea.setText("请输入文本!");
//scroll面板
JScrollPane jScrollPane = new JScrollPane(jTextArea);
contentPane.add(jScrollPane);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,100,100);
this.setVisible(true);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
贪吃蛇
帧,如果时间片足够小,就是动画
键盘监听
定时器 Timmer
StartGame
/**
* 游戏主启动类
* @author 梁吴俊
*/
public class StartGame {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setBounds(10,10,900,720);
//正常的游戏界面都在面板上
jFrame.setResizable(false);
jFrame.add(new GamePanel());
jFrame.setVisible(true);
}
}
Data
//数据中心
public class Data {
//相对路径 tx.jpg
//绝对路径 /相当于当前项目
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 ImageIcon up = new ImageIcon(upURL);
public static URL downURL = Data.class.getResource("statics/down.png");
public static ImageIcon down = new ImageIcon(downURL);
public static URL leftURL = Data.class.getResource("statics/left.png");
public static ImageIcon left = new ImageIcon(leftURL);
public static URL rightURL = Data.class.getResource("statics/right.png");
public static ImageIcon right = new ImageIcon(rightURL);
public static URL bodyURL = Data.class.getResource("statics/body.png");
public static ImageIcon body = new ImageIcon(bodyURL);
public static URL foodURL = Data.class.getResource("statics/food.png");
public static ImageIcon food = new ImageIcon(foodURL);
}
GamePanel
//游戏面板
//键盘监听器
public class GamePanel extends JPanel implements KeyListener, ActionListener {
//定义蛇的数据结构
int length;
//蛇的长度
int[] snakeX = new int[600];
//蛇的x坐标
int[] snakeY = new int[600];
//蛇的y坐标
String fx ;
//食物的坐标
int foodx;
int foody;
Random random = new Random();
//成绩
int source ;
//游戏失败
boolean isFile = false;
//游戏当前的状态:开始,停止
boolean isStart = false;//默认停止
//定时器
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";
//食物随机分布
foodx = 25 + 25 * random.nextInt(34);
foody = 75 + 25 * random.nextInt(24);
source = 0;
}
//绘制面板,游戏中的所有东西,都是用这个画笔来画
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);//清屏
//绘制静态面板
//头部广告栏
this.setBackground(Color.white);
Data.header.paintIcon(this,g,25,11);
//默认的游戏界面
g.fillRect(20,75,850,600);
//画食物
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]);
}
//画得分
g.setFont(new Font("微软雅黑", Font.BOLD,15));
g.drawString("长度:" + length,800,30 );
g.drawString("得分:" + source,800,50 );
//游戏状态
if (isStart == false){
g.setColor(Color.white);
g.setFont(new Font("微软雅黑", Font.BOLD,40));
g.drawString("按下空格开始游戏",250,250);
}
//游戏结束判断
if (isFile){
g.setColor(Color.red);
g.setFont(new Font("微软雅黑", Font.BOLD,40));
g.drawString("游戏结束,按下空格重新开始",250,250);
}
}
/**
* 键盘监听事件
* @param e
*/
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_SPACE){
if (isFile){
isFile = false;
init();
}else{
isStart = !isStart;
repaint();
}
}
//小蛇移动
if (keyCode == KeyEvent.VK_UP){
fx = "U";
}else if (keyCode == KeyEvent.VK_LEFT){
fx = "L";
}else if (keyCode == KeyEvent.VK_RIGHT){
fx = "R";
}else if (keyCode == KeyEvent.VK_DOWN){
fx = "D";
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
//事件监听--需要通过固定事件来刷新,1s = 10次
@Override
public void actionPerformed(ActionEvent e) {
if (isStart && isFile == false){
//如果游戏是开始状态,就让小蛇动起来
//判断是否吃到食物
if (snakeX[0] == foodx && snakeY[0] == foody){
//长度加
length += 1;
//重新随机食物位置
foodx = 25 + 25 * random.nextInt(34);
foody = 75 + 25 * random.nextInt(24);
source++;//加分
}
//移动
for (int i = length-1; i > 0 ;i--) {
//判断失败,如果撞到自己就失败
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
isFile = true;
}
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;
}
}
repaint();//重画页面
}
timer.start();//定时器启动
}
}