GUI知识总结,包含贪吃蛇小游戏

GUI:

一、介绍

(一)简单介绍

Gui的核心技术:Swing 和 AWT 1.因为界面不美观。 2.需要 jre 环境!

为什么我们要学习? 1.可以写出自己心中想要的一些小工具 2.工作时候,也可能需要维护到swing界面,概率极小! 3.了解MVC架构,了解监听!

(二)AWT

(抽象的窗口工具)

包含了很多类和接口,GUI:图形用户界面

image-20220516105156514

2.1 组件和容器

(1)frame

第一个java图像界面窗口:

package com.Yaof.Demo1;

import java.awt.*;

public class Demo01 {

   public static void main(String[] args) {

       Frame frame = new Frame("我的第一个java图像界面窗口");

       //设置可见性
       frame.setVisible(true);

       //设置坐标
       frame.setLocation(300,300);

       //设置大小
       frame.setSize(800,400);

       //设置颜色
       frame.setBackground(Color.pink);

       //设置大小固定
       frame.setResizable(true);
  }
}

多个窗口:(存在问题)

package com.Yaof.Demo1;

import java.awt.*;
import java.util.Set;

public class Demo02 {
   public static void main(String[] args) {
       Demo001 demo001 = new Demo001(300,300,600,400,Color.red);
       Demo001 demo002 = new Demo001(900,300,600,400,Color.orange);
       Demo001 demo003 = new Demo001(300,700,600,400,Color.yellow);
       Demo001 demo004 = new Demo001(900,700,600,400,Color.green);
  }
}
class Demo001 extends Demo01 {
   static int id = 0;//存在多个窗口,需要一个计数器

   public Demo001(int x, int y, int w, int h, Color color) {
/*         super("Frame+"+(++id));//此处有问题
       setLocation(x,y);
       setSize(w,h);
       setBackground(color);*/
        Frame frame = new Frame("Frame"+(++id));
        frame.setBounds(x,y,w,h);//坐标大小
        frame.setBackground(color);
        frame.setVisible(true);

  }
}
(2)面板panel
package com.Yaof.Demo1;

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

public class PanelTest {
   public static void main(String[] args) {
       Frame frame = new Frame("背景");
       Panel panel = new Panel();//新建面板
       Panel panel1= new Panel();//再新建一个面板

       //设置布局,默认置顶
       frame.setLayout(null);

       frame.setBounds(300,300,500,500);//设置坐标大小
       frame.setBackground(new Color(94, 236, 17));

       panel.setBounds(50,50,200,400);
       panel.setBackground(new Color(239, 12, 12));

       panel1.setBounds(250,50,200,400);
       panel1.setBackground(new Color(25, 81, 224));

       frame.add(panel);
       frame.add(panel1);

       frame.setVisible(true);

       //监听事件,监听窗口关闭事件
       //适配器模式:
       frame.addWindowListener(new WindowAdapter() {
           //点击窗口关闭时做的事情
           @Override
           public void windowClosing(WindowEvent e) {
               //结束程序
               System.exit(0);
          }
      });
  }
}

image-20220516161647351

(3)布局管理器
1.流式布局FlowLayout
package com.Yaof.Demo1;

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

public class FlowLayoutTest {
   //流式布局
   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(/*FlowLayout.CENTER*/));//center为默认

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

       frame.setVisible(true);
       frame.setSize(200,200);
  }
}
2、方向BorderLayout
package com.Yaof.Demo1;

import java.awt.*;

public class TestBorderLayout {
   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.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);

       frame.setSize(500,500);
  }
}
3、表格布局GridLayout
package com.Yaof.Demo1;

import java.awt.*;

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

       Button btn1 = new Button("btn1");
       Button btn2 = new Button("btn2");
       Button btn3 = new Button("btn3");
       Button btn4 = new Button("btn4");
       Button btn5 = new Button("btn5");
       Button btn6 = new Button("btn6");

       frame.setVisible(true);

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

       frame.setLayout(new GridLayout(2,3));
       frame.setSize(300,300);

       frame.pack();//较好的排列方法
  }
}

练习:(待完善)

package com.Yaof.Demo1;

import java.awt.*;

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

       Panel panel1 = new Panel(new GridLayout(1,1));
       Panel panel2 = new Panel(new GridLayout(2,1));
       Panel panel3 = new Panel(new GridLayout(1,1));
       Panel panel4 = new Panel(new GridLayout(1,1));
       Panel panel5 = new Panel(new GridLayout(2,2));
       Panel panel6 = new Panel(new GridLayout(1,1));
       Button btn1 = new Button("btn1");
       Button btn2 = new Button("btn2");
       Button btn3 = new Button("btn3");
       Button btn4 = new Button("btn4");
       Button btn5 = new Button("btn5");
       Button btn6 = new Button("btn6");
       Button btn7 = new Button("btn7");
       Button btn8 = new Button("btn8");
       Button btn9 = new Button("btn9");
       Button btn10 = new Button("btn10");
       Button btn01 = new Button("btn01");
       Button btn02 = new Button("btn02");
       Button btn03 = new Button("btn03");

       frame.setVisible(true);
       frame.setBounds(100,100,600,400);
       panel1.setBounds(0,0,100,200);
       panel2.setBounds(100,0,400,200);
       panel3.setBounds(500,0,100,200);
       panel4.setBounds(0,200,100,200);
       panel5.setBounds(100,200,400,200);
       panel6.setBounds(500,200,100,200);

       frame.add(panel1);
       frame.add(panel2);
       frame.add(panel3);
       frame.add(panel4);
       frame.add(panel5);
       frame.add(panel6);

       panel1.add(btn1);
       panel2.add(btn2);
       panel2.add(btn3);
       panel3.add(btn4);
       panel4.add(btn5);
       panel5.add(btn6);
       panel5.add(btn7);
       panel5.add(btn8);
       panel5.add(btn9);
       panel6.add(btn10);

       frame.pack();

       frame.setLayout(new GridLayout(2,3));


  }
}

(4)总结

1.Frame是一个顶级窗口

2.Panel 无法单独显示,必须添加到某个容器中。

3.布局管理器: 1.流式 2.东西南北中 3.表格 4.大小,定位,背景颜色,可见性,监听。

(5)练习

image-20220517095512038

package com.Yaof.Demo1;

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

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

       Frame frame = new Frame();

       Panel p1 = new Panel(new BorderLayout());//定义为方向型
       Panel p2 = new Panel(new GridLayout(2,1));//定义2行1列
       Panel p3 = new Panel(new BorderLayout());//定义为方向型
       Panel p4 = new Panel(new GridLayout(2,2));//定义2行2列

       Button btn1 = new Button("btn1");
       Button btn2 = new Button("btn2");
       Button btn3 = new Button("btn3");
       Button btn4 = new Button("btn4");
       Button btn5 = new Button("btn5");
       Button btn6 = new Button("btn6");

       frame.setVisible(true);
       //整体框架为2行1列
       frame.setLayout(new GridLayout(2,1));
       frame.pack();
       frame.setBounds(200,200,600,400);

       //上半部分
       p1.add(btn1,BorderLayout.EAST);
       p1.add(btn2,BorderLayout.WEST);
       p1.add(p2,BorderLayout.CENTER);

       p2.add(btn3);
       p2.add(btn4);

       //下半部分
       p3.add(btn5,BorderLayout.EAST);
       p3.add(btn6,BorderLayout.WEST);
       p3.add(p4,BorderLayout.CENTER);

       for (int i = 0; i < 4; i++) {
           //p4中装入4个按钮
           p4.add(new Button("for-"+i));//直接new一个按钮,()中是按钮的名称
      }

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

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

 

2.2 事件监听

package com.Yaof.Demo02;

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 TestActionEvent {
public static void main(String[] args) {
//按一下,触发一些事件
Frame frame = new Frame();
Button button = new Button();

//因为addActionListener需要一个ActionListener,所以需要构造一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);

frame.pack();
frame.add(button,BorderLayout.CENTER);
frame.setSize(600,400);
frame.setVisible(true);

closing(frame);

}
//关闭窗口
public static void closing(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("666");//点击按钮输出666
}
}

也可以多个事件公用一个监听

2.3 输入框TextField监听

package com.Yaof.Demo03;

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

public class TestText {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setBounds(100,100,200,220);
myFrame.setVisible(true);
myFrame.setBackground(Color.green);
myFrame.setName("低配QQ");
}
}

class MyFrame extends Frame{
public MyFrame(){
setBounds(100,100,200,220);
TextField textField = new TextField();
add(textField);

MyAction myAction = new MyAction();
textField.addActionListener(myAction);
textField.setVisible(true);
textField.setEchoChar('*');
pack();
}
}

class MyAction implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField) e.getSource();//获得一些资源,返回一个对象
System.out.println(field.getText());//获得输入框的文本
field.setText("");
}
}

(六)简易加法计算器

初始:

package com.Yaof.Demo03;

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

public class TestCalc {
public static void main(String[] args) {
new MyFrame2().setVisible(true);
}
}
class MyFrame2 extends Frame{
public MyFrame2() {
//三个文本框,一个按钮,一个标签
TextField num1 = new TextField(10);//字符数10
TextField num2 = new TextField(10);//字符数10
TextField num3 = new TextField(20);//字符数20

Button button = new Button("=");

Label label = new Label("+");

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

pack();
setVisible(true);
//按钮加入监听
button.addActionListener(new MyActionListener(num1,num2,num3));
}
}
class MyActionListener implements ActionListener{
//获取三个变量
private TextField num1,num2,num3;
public MyActionListener(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
num3.setText(""+(n1+n2));

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

优化1,组合:

package com.Yaof.Demo03;

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

public class TestCalc {
public static void main(String[] args) {
MyFrame2 myFrame2 = new MyFrame2();
myFrame2.setVisible(true);
myFrame2.loadFrame();//调用一下方法,不然不显示计算器了
}
}
class MyFrame2 extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadFrame(){//load加载
//三个文本框,一个按钮,一个标签
num1 = new TextField(10);//字符数10
num2 = new TextField(10);//字符数10
num3 = new TextField(20);//字符数20
Button button = new Button("=");
Label label = new Label("+");

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

pack();
setVisible(true);

button.addActionListener(new MyActionListener(this));
}
}

class MyActionListener implements ActionListener{
MyFrame2 myFrame2 = null;//新建对象 赋初始值
//获取三个变量
public MyActionListener(MyFrame2 myFrame2){
this.myFrame2 = myFrame2;//监听数据传入
}

@Override
//监听数据处理
public void actionPerformed(ActionEvent e) {
//获得加数和被加数
int n1 = Integer.parseInt(myFrame2.num1.getText());
int n2 = Integer.parseInt(myFrame2.num2.getText());

//返回num3
myFrame2.num3.setText(""+(n1+n2));

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

优化2,内部类:

package com.Yaof.Demo03;

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

public class TestCalc {
public static void main(String[] args) {
MyFrame2 myFrame2 = new MyFrame2();
myFrame2.setVisible(true);
myFrame2.loadFrame();//调用一下方法,不然不显示计算器了
}
}
class MyFrame2 extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadFrame(){//load加载
//三个文本框,一个按钮,一个标签
num1 = new TextField(10);//字符数10
num2 = new TextField(10);//字符数10
num3 = new TextField(20);//字符数20
Button button = new Button("=");
Label label = new Label("+");

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

pack();
setVisible(true);

button.addActionListener(new MyActionListener());
}
private class MyActionListener implements ActionListener{
//内部类,直接获得num1,2,3
@Override
public void actionPerformed(ActionEvent e) {
//获得加数和被加数
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());

//返回num3
num3.setText(""+(n1+n2));

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

2.4 画笔paint

package com.Yaof.Paint;

import java.awt.*;

public class TestPaint1 {
public static void main(String[] args) {
new Mypaint().LoadPaint();
}
}
class Mypaint extends Frame{
public void LoadPaint() {
setBounds(200,200,600,400);
setVisible(true);
}
//画笔
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.fillOval(100,100,100,100);//画个实心圆

g.setColor(Color.green);
g.fillRect(150,200,300,150);//画个实心矩形
//养成习惯,画笔用完就还原
}
}

2.5 鼠标监听

实现鼠标点击的画画:

image-20220518164315571

package com.Yaof.Paint;

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

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

class MyFrame extends Frame{

//画画需要画笔,需要监听鼠标当前位置,需要集合来存储这个点
ArrayList points;//存储点

public MyFrame(String title) {
//画板
super(title);
setBounds(200,200,600,400);
setVisible(true);

//存鼠标的点
points =new ArrayList<>();

//鼠标监听器,针对这个窗口
this.addMouseListener(new MyMouse());
}

@Override
public void paint(Graphics g) {
//画笔,监听鼠标的事件
Iterator iterator = points.iterator();//使用迭代器将points中的点迭代出来
while (iterator.hasNext()){
Point point = (Point) iterator.next();
g.setColor(Color.green);
g.fillOval(point.x,point.y,10,10);
}
}

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

//适配器模式
private class MyMouse extends MouseAdapter {
//鼠标监听
@Override
public void mousePressed(MouseEvent e) {
MyFrame frame = (MyFrame) e.getSource();

//这里点击时,会在界面产生一个点;
frame.addPaint(new Point(e.getX(),e.getY()));

//刷新,每次点击鼠标都重新画一遍
frame.repaint();
}
}
}

2.6 窗口监听

package com.Yaof.Listener;

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

public class WindowListener {
public static void main(String[] args) {
new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame() {
setBounds(200,200,600,400);
setVisible(true);
setBackground(Color.blue);
this.addWindowListener(
//匿名内部类
new WindowAdapter() {
/* @Override
public void windowActivated(WindowEvent e) {
System.out.println("激活窗口");
}*/

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

}
});
}

/* //此方法较次,继承类不如内部类
class MyWindowListener extends WindowAdapter{
@Override
public void windowOpened(WindowEvent e) {

}

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

2.7 键盘监听

package com.Yaof.Listener;

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

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

class KeyFrame extends Frame{
public KeyFrame(){
setBounds(200,200,600,400);
setBackground(Color.blue);
setVisible(true);

this.addKeyListener(new KeyAdapter() {
//键盘按下
@Override
public void keyPressed(KeyEvent e) {
//获得键盘按下的键
int KeyCode = e.getKeyCode();
System.out.println(KeyCode);
if(KeyCode==KeyEvent.VK_E){//不用记录KeyCode的具体数值,直接KeyEvent.VK_***
System.out.println("你输入了E");
}

}
});
}
}

(三) Swing

3.1 窗口和面板

package com.Yaof.Demo04;

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

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

//init() 初始化
public void init(){
JFrame jf = new JFrame();
jf.setBounds(100,100,600,400);
jf.setVisible(true);
jf.setBackground(Color.blue);

//设置文字 JLabel
JLabel jLabel = new JLabel("欢迎来到我的世界");
//设置居中
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
jf.add(jLabel);

//新建一个容器
Container container = jf.getContentPane();
container.setBackground(Color.blue);


//关闭窗口
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}

3.2 弹窗JDialog

package com.Yaof.Demo04;

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

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

public DialogDemo() {
//基本属性
this.setBounds(100,100,600,400);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

//容器
Container container = this.getContentPane();
container.setBackground(Color.green);
container.setLayout(null);//绝对布局



JButton jButton = new JButton("点我有弹窗");
jButton.setBounds(30,30,200,50);
jButton.setVisible(true);

container.add(jButton);

//点击按钮时,弹出一个弹窗
jButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
}
);
}
}
class MyDialog extends JDialog{
public MyDialog() {
this.setBounds(100,500,200,200);
this.setVisible(true);

}
}

3.3 标签

3.3.1 Icon图标

需要继承 JFrame 类和 Icon 接口

package com.Yaof.Demo04;

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

public class IconDemo extends JFrame implements Icon {
private int width;
private int height;

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

public void init(){
IconDemo iconDemo = new IconDemo(15,15);
//图标放在标签上,也能放在按钮上
JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(label);

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

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

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

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

public static void main(String[] args) {
new IconDemo().init();
}
}
3.3.2 ImageIcon
package com.Yaof.Demo04;

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

public class ImageIconDemo extends JFrame {

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

ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);//图片放入标签
label.setHorizontalAlignment(SwingConstants.CENTER);//设置居中

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

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


}

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

3.4 面板

3.4.1 JPanel:
package com.Yaof.Demo04;

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

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

public PanelDemo() {
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(2,2,10,10));

JPanel jPanel = new JPanel();

jPanel.add(new JButton("666"));
jPanel.add(new JButton("666"));
jPanel.add(new JButton("666"));
jPanel.add(new JButton("666"));
contentPane.add(jPanel);

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

}
}
3.4.2 JScroll(滚动条):
package com.Yaof.Demo04;

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

public class ScrollDemo extends JFrame {
public static void main(String[] args) {
new ScrollDemo();
}
public ScrollDemo(){
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.yellow);
this.setVisible(true);
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

//文本域
JTextArea jTextArea = new JTextArea(20,50);//超过20,50时,滚动条出现
jTextArea.setText("666");

//JScroll滚动条
JScrollPane jScrollPane = new JScrollPane(jTextArea);
contentPane.add(jScrollPane);
}
}

3.5 按钮

3.5.1 图片按钮
package com.Yaof.Demo04;

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

public class PictureJButton extends JFrame {
public PictureJButton() {
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.green);

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

//获取图片的地址
URL url = PictureJButton.class.getResource("潇洒.jpg");
Icon icon = new ImageIcon(url);//将图片存放到图标icon中
JButton jButton = new JButton();
jButton.setIcon(icon);

contentPane.add(jButton);
}

public static void main(String[] args) {
new PictureJButton();
}
}
3.5.2 单选框 radioButton
package com.Yaof.Demo04;

import javafx.scene.control.RadioButton;

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

public class radioButtonDemo extends JFrame{
public static void main(String[] args) {
new radioButtonDemo();
}
public radioButtonDemo(){
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.yellow);

//新建三个单选按钮
JRadioButton radioButton1 = new JRadioButton("radioButton1");
JRadioButton radioButton2 = new JRadioButton("radioButton2");
JRadioButton radioButton3 = new JRadioButton("radioButton3");

//给按钮分组,实现单选
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);

contentPane.add(radioButton1,BorderLayout.NORTH);
contentPane.add(radioButton2,BorderLayout.CENTER);
contentPane.add(radioButton3,BorderLayout.SOUTH);

this.setVisible(true);
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
3.5.3 多选框 JCheckBox
package com.Yaof.Demo04;

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

public class JCheckBoxDemo extends JFrame {
public static void main(String[] args) {
new JCheckBoxDemo();
}
public JCheckBoxDemo(){
Container contentPane = this.getContentPane();

//新建三个多选框
JCheckBox jCheckBox1 = new JCheckBox("1");
JCheckBox jCheckBox2 = new JCheckBox("2");
JCheckBox jCheckBox3 = new JCheckBox("3");

//设置居中
jCheckBox1.setHorizontalAlignment(SwingConstants.CENTER);
jCheckBox2.setHorizontalAlignment(SwingConstants.CENTER);
jCheckBox3.setHorizontalAlignment(SwingConstants.CENTER);
//放入容器并设置上中下
contentPane.add(jCheckBox1,BorderLayout.NORTH);
contentPane.add(jCheckBox2,BorderLayout.CENTER);
contentPane.add(jCheckBox3,BorderLayout.SOUTH);

contentPane.setBackground(Color.green);
this.setVisible(true);
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}

3.6 列表

3.6.1 下拉框JComboBox

addItem上下选择

package com.Yaof.Demo05;

import com.Yaof.Demo04.JCheckBoxDemo;

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

public class TestComboBoxDemo extends JFrame {
public static void main(String[] args) {
new TestComboBoxDemo();
}
public TestComboBoxDemo(){
Container contentPane = this.getContentPane();

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

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

contentPane.add(status);

contentPane.setBackground(Color.green);
this.setVisible(true);
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
3.6.2 列表框
package com.Yaof.Demo05;

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

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

public TestComboBox2() {
Container contentPane = this.getContentPane();

// String[] container = {"1", "2", "3"};//生成静态列表的内容
Vector container = new Vector();//动态列表
//放入数据
container.add("张三");
container.add("李四");
container.add("3");
container.add("4");
container.add("5");
JList jList = new JList(container);

contentPane.add(jList);

contentPane.setBackground(Color.green);
this.setVisible(true);
this.setBounds(100, 100, 200, 200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}

3.7 文本框、密码框、文本域

3.7.1 文本框
package com.Yaof.Demo05;

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

public class TestJTextField extends JFrame {
public static void main(String[] args) {
new TestJTextField();
}
public TestJTextField(){
Container contentPane = this.getContentPane();
//新建文本框
JTextField jTextField = new JTextField("666啊");
JTextField jTextField1 = new JTextField("777啊");
contentPane.add(jTextField,BorderLayout.NORTH);
contentPane.add(jTextField1,BorderLayout.SOUTH);

contentPane.setBackground(Color.green);
this.setVisible(true);
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
3.7.2 密码框
package com.Yaof.Demo05;

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

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

public TestText01() {
Container contentPane = this.getContentPane();

//设置密码框为*,配合面板使用更好
JPasswordField jPasswordField = new JPasswordField();
jPasswordField.setEchoChar('*');

contentPane.add(jPasswordField);

contentPane.setBackground(Color.green);
this.setVisible(true);
this.setBounds(100, 100, 200, 200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
3.7.3 文本域

代码和面板的滚动条一样

package com.Yaof.Demo04;

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

public class ScrollDemo extends JFrame {
public static void main(String[] args) {
new ScrollDemo();
}
public ScrollDemo(){
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.yellow);
this.setVisible(true);
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

//文本域
JTextArea jTextArea = new JTextArea(20,50);//超过20,50时,滚动条出现
jTextArea.setText("666");

//JScroll滚动条
JScrollPane jScrollPane = new JScrollPane(jTextArea);
contentPane.add(jScrollPane);
}
}

 

贪吃蛇

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

键盘监听

定时器Timer


1、启动类

package com.Yaof.Snack;

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.add(new GamePanel());

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

2、数据类

package com.Yaof.Snack;

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

//数据中心
public class Data {
//相对路径 潇洒.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);


}

3、游戏面板类

package com.Yaof.Snack;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

//游戏的面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
   //定义蛇的数据结构
   int length;//蛇的长度
   int[] snakex = new int[600];//蛇的x坐标25*25
   int[] snakey = new int[500];//蛇的y坐标25*25
   String fx;//初始方向

   int foodx;
   int foody;
   int score;
   Random random = new Random();

   boolean isFail = false;//默认不失败
   //游戏当前的状态:开始、不开始   默认不开始
   boolean isstart = false;

   //定时器,以ms毫秒为单位
   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);

       score=0;

  }

   //绘制面板,游戏中的所有组件都由这个画笔来画
   @Override
   protected void paintComponent(Graphics g) {
       super.paintComponent(g);//清屏

       //绘制静态的面板
       Data.header.paintIcon(this,g,25,11);//头部广告栏
       setBackground(Color.white);
       g.fillRect(25,75,850,600);//默认游戏界面

       Data.right.paintIcon(this,g,snakex[0],snakey[0]);//蛇头初始化
       for (int i = 1; i < length; i++) {
           Data.body.paintIcon(this,g,snakex[i],snakey[i]);//身体
      }
       /*Data.body.paintIcon(this,g,snakex[1],snakey[1]);//身体
       Data.body.paintIcon(this,g,snakex[2],snakey[2]);//第二个身体坐标*/

       //画积分
       g.setColor(Color.green);
       g.setFont(new Font("微软雅黑",Font.BOLD,18));
       g.drawString("长度"+length,750,30);
       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]);
      }

       //游戏状态
       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);
      }
  }



   //事件监听--需要通过固定的时间刷新,1s 10次
   @Override
   public void actionPerformed(ActionEvent e) {
       if(isstart&&isFail==false){//如果开始状态,就启动监听
           //吃食物
           if(snakex[0]==foodx && snakey[0]==foody){
               length++;//长度+1
               //分数+10
               score = 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]>825){
                   isFail=true;
//                   snakex[0]=25;
              }
          }else if(fx.equals("L")){
               snakex[0]=snakex[0]-25;
               if(snakex[0]<50){
                   isFail=true;
//                   snakex[0]=850;
              }
          }else if(fx.equals("U")){
               snakey[0]=snakey[0]-25;
               if(snakey[0]<100){
                   isFail=true;
//                   snakey[0]=650;
              }
          }else if(fx.equals("D")){
               snakey[0]=snakey[0]+25;
               if(snakey[0]>650){
                   isFail=true;
//                   snakey[0]=75;
              }
          }
           //失败判断,撞到自己就算失败
           for (int i = 1; i < length; i++) {
               if(snakex[0]==snakex[i] && snakey[0]==snakey[i]){
                   isFail=true;
              }
          }
           
           repaint();//重画页面
      }
       timer.start();
  }

   //键盘监听器
   @Override
   public void keyPressed(KeyEvent e) {
       int keycode = e.getKeyCode();
       if(keycode==KeyEvent.VK_SPACE){
           if(isFail){
               //重新开始
               isFail = false;
               init();
          }
           isstart = !isstart;//取反
           repaint();
      }

       //蛇不能后退,小蛇方向
       if (keycode == KeyEvent.VK_UP&& !fx.equals("D")){
           fx = "U";
      }else
       if (keycode == KeyEvent.VK_DOWN&& !fx.equals("U")){
           fx = "D";
      }else if (keycode == KeyEvent.VK_RIGHT&& !fx.equals("L")){
           fx = "R";
      }else if (keycode == KeyEvent.VK_LEFT&& !fx.equals("R")){
           fx = "L";
      }


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

}
posted @ 2022-06-15 10:17  爱吃蘋果  阅读(26)  评论(0)    收藏  举报