GUI编程入门到游戏实战

GUI编程

组件

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

1. 简介

GUI的核心技术 :Swing,AWT

  • 因为界面不美观
  • 需要jar环境

有什么用?

  • 可以写一些小具
  • 工作时候可能需要维护swing界面,概率极小
  • 了解MVC架构,了解监听

2. AWT

2.1 AWT介绍

  • 包含了很多类和接口!GUI!
  • 元素:窗口,按钮,文本框
  • java.awt

在这里插入图片描述

2.2 组件和容器

2.2.1. Frame
package 第一个Frame窗口;

import java.awt.*;

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

运行效果图
在这里插入图片描述
问题:发现窗口关闭不掉,停止java程序
尝试回顾封装

package 第一个Frame窗口;

import java.awt.*;

public class TestFrame01 {
    public static void main(String[] args) {
        MyFrame MyFrame01=new MyFrame(100,100,300,300,Color.red);
        MyFrame MyFrame02=new MyFrame(400,100,300,300,Color.yellow);
        MyFrame MyFram03=new MyFrame(100,400,300,300,Color.green);
        MyFrame MyFrame04=new MyFrame(400,400,300,300,Color.blue);

    }
}
class MyFrame extends Frame{
    static int id=0;//可能存在多个窗口,需要一个计时器
    public MyFrame(int x,int y,int w,int h,Color color){
        super("MyFrame"+(++id));
        setBackground(color);
        setVisible(true);
//        setSize(x,y);
//        setLocation(w,h);
        setBounds(x,y,w,h);
    }
}

在这里插入图片描述

2.2.2. Panel面板

解决了关闭事件

package Panel面板;

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

//Panel可以看成是一个空间,但是不能单独存在
public class TestPanel {
    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(new Color(120, 239, 46, 255));
        //panel设置坐标,相对于frame
        panel.setBounds(50,50,400,400);
        panel.setBackground(new Color(239, 93, 93));
        //frame.add(panel)
        frame.add(panel);
        frame.setVisible(true);//设置是否可见
        //监听事件,监听窗口关闭事件,System.exit(0),强行关闭,正常关闭,,,exit(0),异常关闭
        //适配器模式
        frame.addWindowListener(new WindowAdapter() {
            //窗口点击关闭时需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }
}

在这里插入图片描述

2.3 布局管理器

  • 流式布局
  • 东西南北中
  • 表格布局

流式布局

package FlowLayOut;

import java.awt.*;

/**
 * 3种布局管理器
 * (1)流式布局
 * (2)东西南北中
 * (3)表格布局
 *
 */
public class TestFlowLayOut {
    public static void main(String[] args) {
        Frame frame=new Frame();
        /**
         * 流式布局
         */
        //组件,按钮
        Button button = new Button("button");
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        //设置为流式布局
//        frame.setLayout(new FlowLayout());//FlowLayout.CENTER
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
//        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
        frame.setSize(200,200);
        //把按钮添加上去
        frame.add(button);
        frame.add(button1);
        frame.add(button2);
        frame.setVisible(true);
    }
}

在这里插入图片描述
东西南北中

package 布局管理器;

import java.awt.*;

import static java.awt.BorderLayout.*;

/**
 * 东西南北中
 */
public class TestBorderLayOut {
    public static void main(String[] args) {
        Frame frame=new Frame("TestBorderLayout");

        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.add(east,EAST);
//        frame.add(west,WEST);
//        frame.add(south,SOUTH);
//        frame.add(north,NORTH);
//        frame.add(center,CENTER);
        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(200,200);
        frame.setVisible(true);
    }
}

在这里插入图片描述
表格布局 Grid

package 布局管理器;

import java.awt.*;

/**
 * 表格布局
 */
public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame=new Frame("TestGridLayout");

        Button grid1 = new Button("grid1");
        Button grid2 = new Button("grid2");
        Button grid3 = new Button("grid3");
        Button grid4 = new Button("grid4");
        Button grid5 = new Button("grid5");
        Button grid6 = new Button("grid6");
        frame.setLayout(new GridLayout(3,2));
        frame.add(grid1);
        frame.add(grid2);
        frame.add(grid3);
        frame.add(grid4);
        frame.add(grid5);
        frame.add(grid6);
        frame.pack();//Java函数
        frame.setVisible(true);
}
}


思考在这里插入图片描述
分析过程在这里插入图片描述
代码实现

package 布局管理器;

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

/**
 * 练习
 */
public class Exercise {
    public static void main(String[] args) {
        //总窗口
        Frame frame=new Frame("Exercise");
        frame.setSize(400,300);
        frame.setBackground(new Color(1,1,1));
        frame.setLocation(500,300);
        frame.setVisible(true);
        //分
        frame.setLayout(new GridLayout(2,1));
        //上板面
        Panel p1=new Panel(new BorderLayout());
        Panel p2=new Panel(new GridLayout(2,1));
        p1.add(new Button("east-1"),BorderLayout.EAST);
        p1.add(new Button("west-1"),BorderLayout.WEST);
        p2.add(new Button("north-1"));
        p2.add(new Button("north-2"));
        //下板面
        Panel p3=new Panel(new BorderLayout());
        Panel p4=new Panel(new GridLayout(2,2));
        p3.add(new Button("east-2"),BorderLayout.EAST);
        p3.add(new Button("west-2"),BorderLayout.WEST);
        for (int i = 0; i < 4; i++) {
            p4.add(new Button("south-"+i));
        }
        //组合
        p1.add(p2,BorderLayout.CENTER);
        p3.add(p4,BorderLayout.CENTER);
        frame.add(p1);
        frame.add(p3);
        //监听关闭窗口
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

在这里插入图片描述

总结
  1. Frame是一个顶级窗口
  2. Panel无法单独显示,必须添加到某个容器中
  3. 布局管理器
    1. 流式布局
    2. 东西南北中
    3. 表格
  4. 大小,定位,背景颜色,可见性,监听!

2.4 事件监听

事件监听:当某个事件发生的时候,干什么?

package 事件监听;

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("TestActionEvent");
        Button button=new Button("button");
        //因为addActionListener()需要一个ActionListener,所以我们需要构建一个ActionListener
        MyActionListenner myActionListenner=new MyActionListenner();
        button.addActionListener(myActionListenner);

        frame.add(button,BorderLayout.CENTER);
        frame.pack();

        windowClose(frame);//关闭窗口
        frame.setVisible(true);
    }
    //关闭窗口事件
    public static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

//事件监听
class MyActionListenner implements ActionListener{

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

多个按钮,共享一个事件

package 事件监听;

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

/**
 * 两个按钮,实现同一个监听
 */
public class TestActionEvent02 {
    public static void main(String[] args) {
        //开始  停止
        Frame frame=new Frame("开始-停止");
        Button start = new Button("start");
        Button stop = new Button("stop");
        //可以定义触发所显示返回的信息,如果不定义,则会走默认值!
        stop.setActionCommand("button-stop");
        //可以多个按钮只写一个监听类,按钮可根据监听类,判断按钮实现的操作
        MyMonitor myMonitor = new MyMonitor();
        start.addActionListener(myMonitor);
        stop.addActionListener(myMonitor);
        frame.add(start,BorderLayout.NORTH);
        frame.add(stop,BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }
}
//事件监听
class MyMonitor implements ActionListener{

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

        }
    }
}

2.5 输入文本框TextField监听

package 事件监听;

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 TestText01 {
    public static void main(String[] args) {
        //启动
        new MyFrame();
    }
}
class MyFrame extends Frame{
    public  MyFrame(){
        TextField textField=new TextField();
        add(textField);
        //监听这个文本框输入的文字
        MyActionListener01 myActionListener01 = new MyActionListener01();
        //按下回车就会触发这个输入框的事件
        textField.addActionListener(myActionListener01);
        //设置替换编码
        textField.setEchoChar('*');//设置编码格式,一般用于隐藏密码
        pack();
        setVisible(true);
        windowsClose( this);
    }
    public  static void windowsClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
class MyActionListener01 implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field=(TextField) e.getSource();//获的一些资源
        System.out.println(field.getText());//获得文本框的文本
        field.setText("");
    }
}

2.6 简易计算机,组合+内部类回顾复习!

oop(面向对象)原则:先组合,大于继承!
在这里插入图片描述
目前代码

package 事件监听;

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

/**
 * 简易计算器
 */
public class TestCalculator {
    public static void main(String[] args) {
//        new Calculator();
        TestActionEvent.windowClose(new Calculator());//直接调用之间创建的窗口关闭事件
    }
}
//计算器类
class Calculator extends Frame{
    public Calculator() {
        //3个文本框
        TextField textField1 = new TextField(10);//字符数
        TextField textField2 = new TextField(10);
        TextField textField3 = new TextField(20);
        //一个按钮
        Button button = new Button("=");
        button.addActionListener(new MyCalculatorListener(textField1,textField2,textField3));
        //一个标签
        Label label = new Label("+");
        //布局
        setLayout(new FlowLayout());
        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);
        pack();
        setVisible(true);
    }
}
class MyCalculatorListener implements ActionListener{
    //获取三个变量
    private TextField textField1,textField2,textField3;
    public MyCalculatorListener(TextField textField1,TextField textField2,TextField textField3){
        this.textField1=textField1;
        this.textField2=textField2;
        this.textField3=textField3;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取加数和被加数
        //parseInt将字符串参数作为有符号的十进制整数进行解析
        int n1=Integer.parseInt(textField1.getText());
        int n2=Integer.parseInt(textField2.getText());
        //将这个值+法运算后,放到第三个框
        textField3.setText(""+(n1+n2));
        //清除前两个框
        textField1.setText("");
        textField2.setText("");
    }
}

完全改造成面向对象写法

package 事件监听;

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

public class TestCalculator02 {
    public static void main(String[] args) {
        new Calculator01().loadFrame();
    }
}
//计算器类
class Calculator01 extends Frame {
    //属性
    TextField textField1,textField2,textField3;
    //方法
    public void loadFrame(){
        textField1=new TextField(10);
        textField2=new TextField(10);
        textField3=new TextField(20);
        Button button = new Button("=");
        Label label = new Label("+");
        button.addActionListener(new MyCalculatorListener01(this));
        //布局
        setLayout(new FlowLayout());
        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);
        pack();
        setVisible(true);
    }
}

class MyCalculatorListener01 implements ActionListener {
    //获取计算机这个对象,在一个类中组合另外一个类
    Calculator01 calculator01=null;
    public MyCalculatorListener01(Calculator01 calculator01){
        this.calculator01=calculator01;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取加数和被加数
        //将这个值+法运算后,放到第三个框
        //清除前两个框
        int n1=Integer.parseInt(calculator01.textField1.getText());
        int n2=Integer.parseInt(calculator01.textField2.getText());
        calculator01.textField3.setText(""+(n1+n2));
        calculator01.textField1.setText("");
        calculator01.textField2.setText("");
    }
}

内部类:

  • 更好的包装
  • 内部类最好的方法,就是可以畅通无阻的访问外部类的属性和方法!
package 事件监听;

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

public class TestCalculator03 {
    public static void main(String[] args) {
        new Calculator02().loadFrame();
    }
}
//计算器类
class Calculator02 extends Frame {
    //属性
    TextField textField1,textField2,textField3;
    //方法
    public void loadFrame(){
        textField1=new TextField(10);
        textField2=new TextField(10);
        textField3=new TextField(20);
        Button button = new Button("=");
        Label label = new Label("+");
        button.addActionListener(new MyCalculatorListener02());
        //布局
        setLayout(new FlowLayout());
        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);
        pack();
        setVisible(true);
    }
    //监听器
    private  class MyCalculatorListener02 implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            //获取加数和被加数
            //将这个值+法运算后,放到第三个框
            //清除前两个框
            int n1=Integer.parseInt(textField1.getText());
            int n2=Integer.parseInt(textField2.getText());
            textField3.setText(""+(n1+n2));
            textField1.setText("");
            textField2.setText("");
        }
    }
}

在这里插入图片描述

2.7 画笔

package 画笔Paint;

import java.awt.*;

/**
 * 画笔
 */
public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}
class MyPaint extends Frame{
    public void loadFrame(){
        setBounds(200,200,600,400);
        setVisible(true);
    }
    //画笔

    @Override
    public void paint(Graphics g) {
        //画笔,需要有颜色,画笔可以画画
//        g.setColor(new Color(157, 3, 253, 255));
        g.drawOval(100,100,100,100);
        g.fillOval(100,200,200,200);//实心的圆

//        g.setColor(Color.RED);
        g.fillRect(200,100,200,200);
        //养成习惯,画笔用完,将他还原到最初的颜色
    }
}

2.8 鼠标监听

目的:想要实现鼠标画画
在这里插入图片描述

package 鼠标监听;

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

/**
 *鼠标监听事件
 */
public class TestMouseListener {
    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());
    }

    @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 addPaint(Point point){
        points.add(point);
    }
    //适配器模式
    private class MyMouseListener extends MouseAdapter{
        @Override
        public void  mousePressed(MouseEvent e) {
            MyFrame frame=(MyFrame)e.getSource();
            //这个点击时,就会在界面上产生一个点!画
            //这个点就是鼠标的点
            frame.addPaint(new Point(e.getX(),e.getY()));
            //每次点击鼠标都需要重新画一遍
            frame.repaint();
        }
    }
}

2.9 窗口监听

package 窗口监听;

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

public class TestWindow {
    public static void main(String[] args) {
        new WindowsFrame("窗口监听");
    }
}
class WindowsFrame extends Frame{
    public WindowsFrame(String title){
        super(title);
        setBackground(Color.yellow);
        setBounds(100,100,400,400);
        setVisible(true);
        addWindowListener(new WindowAdapter() {//匿名内部类
            @Override
            //关闭窗口
            public void windowClosing(WindowEvent e) {
                setVisible(false);//隐藏窗口
//                System.exit(0);
                System.out.println("windowClosing");
            }
            //激活窗口
            @Override
            public void windowActivated(WindowEvent e) {
                WindowsFrame windowsFrame=(WindowsFrame) e.getSource();
                windowsFrame.setTitle("被激活了");
                System.out.println("windowActivated");
            }
        });
    }
}

2.10 键盘监听

package 键盘监听;

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

/**
 * 键盘监听
 */
public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame("键盘监听");
    }
}
class KeyFrame extends Frame{
    public KeyFrame(String title){
        super(title);
        setBackground(new Color(255, 251, 0));
        setBounds(100,100,400,400);
        setVisible(true);
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode=e.getKeyCode();
                System.out.println(keyCode);
                if (keyCode==KeyEvent.VK_UP)
                System.out.println("你按压了上键");
            }
        });
    }
}

3. Swing

3.1 窗口、面板

package Swing之JFrame窗体;

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

//
public class TestJFrame {
    //init();初始化
    public void init(){
        //顶级窗口
        JFrame jFrame=new JFrame("这是一个JFrame窗口");
        jFrame.setBounds(100,100,400,400);
        jFrame.setVisible(true);
        //设置文字JLabel
        JLabel jLabel=new JLabel("这是我创建的第一个JFrame窗口");
        jFrame.add(jLabel);
        //让文本标签居中,设置水平对齐
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        //容器
        jFrame.getContentPane().setBackground(Color.yellow);//背景颜色需要设置在容器中
        //关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

3.2 弹窗

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

package JDialog弹窗;

import Swing之JFrame窗体.TestJFrame;

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

//主窗口
public class TestJDialog extends JFrame {
    public TestJDialog(String title){
        super(title);
        this.setVisible(true);
        this.setBounds(100,100,400,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //JFrame放东西,容器
        Container  container=this.getContentPane();//Container集装箱
        //绝对布局
        container.setLayout(null);
        //按钮
        JButton button = new JButton("点击我,弹出一个新弹窗");
        button.setBounds(50,50,200,60);
        container.add(button);
        //创建按钮监听事件,点击一个按钮时,弹出一个弹窗
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new FirstDialog();
            }
        });

    }

    public static void main(String[] args) {
        new TestJDialog("主窗口");
    }
}
class FirstDialog extends JDialog{
    public FirstDialog(){
        this.setVisible(true);
        this.setBounds(300,300,400,400);
        Container  container= this.getContentPane();//Container集装箱
//        container.setBackground(Color.yellow);
        container.add(new Label("我是弹窗"));

    }
}

3.3 标签

label

new JLabel("xxx")

图标 ICON

package IconImageIcon标签;

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

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

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

    @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 TestIcon().init();
    }
    public void init(){
        TestIcon testIcon =new TestIcon(15,15);
        //图标可以放在标签上,也可以放在按钮上
        JLabel jLabel=new JLabel("icontest",testIcon,SwingConstants.CENTER);
        Container container= getContentPane();
        container.add(jLabel);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述

图片 ImageIcon

package IconImageIcon标签;

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

public class TestImageIcon extends JFrame {
    public static void main(String[] args) {
        new TestImageIcon();
    }
    public TestImageIcon (){
        //获取图片地址
        JLabel jLabel=new JLabel("ImageIcon");
        URL url=TestImageIcon.class.getResource("下载.jpg");
        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);
    }
}

在这里插入图片描述

3.4 面板

JPanel

package 文本域JScroll面板;

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

public class TestJPanel extends JFrame {
    public TestJPanel(String title){
        super(title);
        Container container=getContentPane();
        container.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("2"));
        jPanel2.add(new Button("2"));
        jPanel3.add(new Button("3"));
        jPanel3.add(new Button("3"));
        jPanel4.add(new Button("4"));
        jPanel4.add(new Button("4"));
        jPanel4.add(new Button("4"));
        jPanel4.add(new Button("4"));
        jPanel4.add(new Button("4"));
        jPanel4.add(new Button("4"));
        container.add(jPanel1);
        container.add(jPanel2);
        container.add(jPanel3);
        container.add(jPanel4);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestJPanel("JPanel面板");
    }
}

在这里插入图片描述
JScrollPanel面板(可滚动面板)

package 文本域JScroll面板;

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

/**
 * 滚屏
 */
public class TestJScroll extends JFrame {
    public static void main(String[] args) {
        new TestJScroll("JScrollPanel");
    }
    public TestJScroll(String title){
        super(title);
        Container container=getContentPane();
        //文本域
        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("开启你的Java之旅");
        //Scroll面板
        JScrollPane jScrollPane = new JScrollPane(textArea);
        container.add(jScrollPane);
        setVisible(true);
        setBounds(100,100,400,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }
}

在这里插入图片描述

3.5 按钮

图片按钮

package 图片按钮单选框多选框;

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

/**
 * 图片按钮
 */
public class TestJButton extends JFrame {
    public static void main(String[] args) {
        TestJButton testJButton=new TestJButton();
    }
    public TestJButton(){
        Container container=this.getContentPane();
        //将一个图片变成一个图标
        URL url=TestJButton.class.getResource("下载.jpg");
        ImageIcon imageIcon = new ImageIcon(url);
        //将图片放在按钮上
        JButton jbutton = new JButton("按钮");
        jbutton.setIcon(imageIcon);
        jbutton.setToolTipText("图片按钮");
        container.add(jbutton);
        this.setVisible(true);
        this.setBounds(100,100,400,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述

  • 单选按钮
package 图片按钮单选框多选框;

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

/**
 * 单选框,单选按钮
 */
public class TestJButton02 extends JFrame {
    public static void main(String[] args) {
        new TestJButton02();
    }
    public TestJButton02(){
        Container container=this.getContentPane();
        //单选框
        JRadioButton jRadioButton1 = new JRadioButton("jRadioButton1");
        JRadioButton jRadioButton2 = new JRadioButton("jRadioButton2");
        JRadioButton jRadioButton3 = new JRadioButton("jRadioButton3");
        //由于单选框只能选一个,分组,一个分组中只能选一个
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);
        buttonGroup.add(jRadioButton3);
        container.add(jRadioButton1,BorderLayout.NORTH);
        container.add(jRadioButton2,BorderLayout.CENTER);
        container.add(jRadioButton3,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setBounds(100,100,400,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述

  • 复选按钮
package 图片按钮单选框多选框;

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

public class TestJButton03 extends JFrame {
    public static void main(String[] args) {
        new TestJButton03();
    }
    public TestJButton03(){
        Container container=this.getContentPane();
        //多选框
        JCheckBox jCheckBox1 = new JCheckBox("jCheckBox1");
        JCheckBox jCheckBox2 = new JCheckBox("jCheckBox2");
        container.add(jCheckBox1,BorderLayout.NORTH);
        container.add(jCheckBox2,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setBounds(100,100,400,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述

3.6 列表

  • 下拉框
package 下拉框列表框;

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

/**
 * 下拉框
 */
public class TestCombobox extends JFrame {
    public static void main(String[] args) {
        new TestCombobox();
    }
    public TestCombobox(){
        Container contentPane = getContentPane();
        JComboBox<Object> objectJComboBox = new JComboBox<>();
        objectJComboBox.addItem(null);
        objectJComboBox.addItem("语文");
        objectJComboBox.addItem("数学");
        objectJComboBox.addItem("英语");
        contentPane.add(objectJComboBox);
        pack();
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述

  • 列表框
package 下拉框列表框;

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

public class TestCombobox02 extends JFrame {
    public static void main(String[] args) {
        new TestCombobox02();
    }
    public TestCombobox02(){
        Container contentPane = getContentPane();
        //生成列表的内容
        //添加静态数据
//        String[] string={"张三","李四","王五"};
        //添加动态数据
        Vector<Object> objects = new Vector<>();
        objects.add("张三");
        objects.add("李四");
        objects.add("王五");
//        JList<Object> objectJList = new JList<>(string);
        JList<Object> objectJList = new JList<>(objects);
        contentPane.add(objectJList);
        pack();
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述
应用场景

  • 选择地区,或者一些单个选项
  • 列表,展示信息,一般是动态扩容!

3.7 文本框

  • 文本框
package 文本框密码框文本域;

import 下拉框列表框.TestCombobox02;

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

/**
 * 文本框
 */
public class TestText01 extends JFrame {
    public static void main(String[] args) {
        new TestText01();
    }
    public TestText01(){
        Container contentPane = getContentPane();
        JTextField jTextField1 = new JTextField("欢迎来到Java的世界");
        JTextField jTextField2 = new JTextField("开启Java之旅",20);
        contentPane.add(jTextField1,BorderLayout.NORTH);
        contentPane.add(jTextField2,BorderLayout.SOUTH);
        pack();
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述

  • 密码框
package 文本框密码框文本域;

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

public class TestText02 extends JFrame {
    public static void main(String[] args) {
        new TestText02();
    }
    public TestText02(){
        Container contentPane = getContentPane();
        JPasswordField jPasswordField = new JPasswordField();//默认为:******
        jPasswordField.setEchoChar('*');
        contentPane.add(jPasswordField);
        pack();
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在这里插入图片描述

  • 文本域
package 文本域JScroll面板;

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

/**
 * 滚屏
 */
public class TestJScroll extends JFrame {
    public static void main(String[] args) {
        new TestJScroll("JScrollPanel");
    }
    public TestJScroll(String title){
        super(title);
        Container container=getContentPane();
        //文本域
        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("开启你的Java之旅");
        //Scroll面板
        JScrollPane jScrollPane = new JScrollPane(textArea);
        container.add(jScrollPane);
        setVisible(true);
        setBounds(100,100,400,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }
}

在这里插入图片描述

4. 贪吃蛇

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

package 贪吃蛇;

import javax.swing.*;

/**
 * 游戏的主启动类
 */
public class StartGame {
    public static void main(String[] args) {
        JFrame jFrame=new JFrame("贪吃蛇");
        jFrame.setBounds(10,10, 900,720);
        //正常游戏界面通常都是在面板上
        jFrame.add(new GameJPanel());
        jFrame.setVisible(true);
        jFrame.setResizable(false);//窗口大小不可变
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

package 贪吃蛇;

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

/**
 * 数据中心
 */
public class Data {
    //相对路径 tx.jpg
    //绝对路径   /相当于当前的项目
    public static URL headerurl=Data.class.getResource("Static/header.png");
    public static ImageIcon header=new ImageIcon(headerurl);
    public static URL upurl=Data.class.getResource("Static/head.jpg");
    public static URL downurl=Data.class.getResource("Static/head.jpg");
    public static URL lefturl=Data.class.getResource("Static/head.jpg");
    public static URL righturl=Data.class.getResource("Static/head.jpg");
    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=Data.class.getResource("Static/body.jpg");
    public static  ImageIcon body=new ImageIcon(bodyurl);
    public static URL foodurl=Data.class.getResource("Static/food.png");
    public static ImageIcon food=new ImageIcon(foodurl);
}

package 贪吃蛇;

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

import static javafx.scene.input.KeyCode.Y;
import static javafx.scene.input.KeyCode.getKeyCode;

/**
 * 游戏的面板
 */
public class GameJPanel extends JPanel implements KeyListener, ActionListener {
    //定义蛇的数据结构
    int length;//蛇的长度
    int[] snakeX=new int[600];//蛇的X坐标
    int[] snakeY=new int[500];//蛇的Y坐标
    String fx;
    //食物的坐标
    int foodX;
    int foodY;
    Random random=new Random();
    //游戏当前的状态:开始,停止
    Boolean isStart=false;//默认是不开始
    //设置游戏是否失败
    Boolean isFail=false;
    //设置积分
    int score;
    //定时器
    Timer timer=new Timer(100,this);//以毫秒为单位,100毫秒执行一次
    //构造器
    public GameJPanel(){
        init();
        //获得焦点和键盘事件
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();//游戏一开始就启动
    }
    //初始化方法
    public void init(){
        length=3;
        fx = "R";//初始方向向右
        snakeX[0]=100;snakeY[0]=100;//脑袋的坐标
        snakeX[1]=75;snakeY[1]=100;//第一个身体的坐标
        snakeX[2]=50;snakeY[2]=100;//第二个身体的坐标
        //把食物随机分布在界面上
        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,10);
        g.fillRect(25,75,850,600);//默认的游戏界面
        this.setBackground(Color.WHITE);
        //画积分
        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,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));//设置字体的名字,样式(BOLD粗),大小
            g.drawString("按下空格开始游戏",300,300);
        }
        if (isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体的名字,样式(BOLD粗),大小
            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";
        }
        if (keyCode==KeyEvent.VK_DOWN){
            fx="D";
        }
        if (keyCode==KeyEvent.VK_LEFT){
            fx="L";
        }
        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=score+10;
                //再次随机生成食物
                foodX=25+25*random.nextInt(34);
                foodY=75+25*random.nextInt(24);
            }
            //y移动
            for (int i=length-1;i>0;i--){//及后一节移到前一节位置, snakeX[1]=snakeX[0]
                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;
                }
            }
            if (fx.equals("L")){
                snakeX[0]=snakeX[0]-25;
                //边界判断
                if (snakeX[0]<25){
                    snakeX[0]=850;
                }
            }
            if (fx.equals("U")){
                snakeY[0]=snakeY[0]-25;
                //边界判断
                if (snakeY[0]<75){
                    snakeY[0]=650;
                }
            }
            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();//定时器开启
    }
}

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

故笙~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值