阿小冷学计算机(3)

GUI编程入门到游戏实战

(b站搜索遇见狂神说)
注意:跳过部分视频

AWT

1、组件和容器

注意一定一定要加 import java.awt.*;

import java.awt.*;
//GUI的第一个窗口
public class TestFrame {
    public static void main(String[] args) {
        //Frame JDK 看源码
        Frame frame = new Frame("我的第一关Java图像界面窗口");

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

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

        //设置背景颜色 Color
        frame.setBackground(new Color(1,1,1));


        //弹出的初始位置
        frame.setLocation(200,200);

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

在这里插入图片描述问题:发现窗口关不掉,停止java程序即可

尝试回归封装(多个窗口的创建)

import java.awt.*;
public class TestFrame2 {
    public static void main(String[] args) {
        //展开多个窗口 new
        new MyFrame(100,100,200,200,Color.blue);
        new MyFrame(300,100,200,200,Color.yellow);
        new MyFrame(100,300,200,200,Color.red);
        new MyFrame(300,300,200,200,Color.black);
    }
}

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);
        setBounds(x,y,w,h);
        setVisible(true);
    }
}

在这里插入图片描述

2、面板

解决关闭事件!!!

        Frame frame=new Frame();

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

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

        //坐标
        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(40,160,35));

        //panel 设置坐标 相对于frame
        panel.setBounds(50,50,400,400);
        panel.setBackground(new Color(190,15,60));

        //frame.add(panel)
        frame.add(panel);

        frame.setVisible(true);

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

在这里插入图片描述

3、布局管理器

  • 流式布局
public static void main(String[] args) {
        Frame frame=new Frame();


        //组件-按钮
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("buttom3");

        //设置为流式布局
        //frame.setLayout(new FlowLayout());   //居中
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));

        frame.setSize(200,200);

        //把按钮添加上去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);


        frame.setVisible(true);

        //监听事件,监听窗口关闭事件 System.exit(0)
        //设配器模式
        frame.addWindowListener(new WindowAdapter() {
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //super.windowClosing(e);
                //结束程序
                System.exit(0);
            }
        });
    }
  • 东西南北中
    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,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);
    }
  • 表格布局
在这里插入代    public static void main(String[] args) {
        Frame frame = new Frame("TestGridLayout");

        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.setLayout(new GridLayout(3,2));

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

        frame.pack();  //java函数作用:自动选择最优布局
        frame.setVisible(true);
    }码片

练习:

    public static void main(String[] args) {
       //总 Frame
        Frame frame = new Frame();
        //frame.pack();
        frame.setVisible(true);
        frame.setLocation(300,400);
        frame.setBackground(Color.black);
        frame.setSize(500,300);
        frame.setLayout(new GridLayout(2,1));
//        Button south=new Button("South");
//        Button north=new Button("North");
        frame.add(south,BorderLayout.SOUTH);
        frame.add(north,BorderLayout.NORTH);
//        Button btn1=new Button("btn1");
//        Button btn2=new Button("btn2");
//        frame.setLayout(new GridLayout(2,1));
//
//        frame.add(btn1);
//        frame.add(btn2);
        //4个面板
        Panel p1 = new Panel(new BorderLayout());
        Panel p2 = new Panel(new GridLayout(2,1));
        Panel p3 = new Panel(new BorderLayout());
        Panel p4 = new Panel(new GridLayout(2,2));

        //上面部分
        p1.add(new Button("East-1"),BorderLayout.EAST);
        p1.add(new Button("West-1"),BorderLayout.WEST);
        p2.add(new Button("p2-btn-1"));
        p2.add(new Button("p2-btn-2"));
        p1.add(p2,BorderLayout.CENTER);

        //下面部分
        p3.add(new Button("East-2"),BorderLayout.EAST);
        p3.add(new Button("West-2"),BorderLayout.WEST);
        p4.add(new Button("p4-btn-1"));
        p4.add(new Button("p4-btn-2"));
        p4.add(new Button("p4-btn-3"));
        p4.add(new Button("p4-btn-4"));
        p3.add(p4,BorderLayout.CENTER);


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

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

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

我自己在做这个作业的时候想到了用东西布局和表格,但将他们嵌套在一起我们想明白,卡了一(亿)会!!!

4、事件监听

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.add(button,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);

        windowClose(frame);//关闭窗口
    }

    //关闭窗体的事件
    private static void windowClose(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("aaa");
    }

多个按钮,共享一个事件

public static void main(String[] args) {
        //两个按钮,实现同一个监听
        //开始   停止
        Frame frame = new Frame("开始-停止");
        Button button1 = new Button("start");
        Button button2 = new Button("stop");

        //可以显示的定义触发会返回的命令
        button2.setActionCommand("button2-stop");

        MyMonitor myMonitor = new MyMonitor();
        button1.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);

        frame.add(button1,BorderLayout.NORTH);
        frame.add(button2,BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }
}


class MyMonitor implements ActionListener{
    public void actionPerformed(ActionEvent e){
        //e.getActionCommand() 获得按钮的信息
        System.out.println("按钮被点击了:msg"+e.getActionCommand());
    }

输入框TextField

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

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

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

        //设置替换编码
        textField.setEchoChar('*');

        setVisible(true);
        pack();
    }
}

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

简易计算器,组合+内部类回顾复习

oop原则:组合 大于 继承

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        new Calculator();
    }
}

//计算器类
class Calculator extends Frame {
    public Calculator(){
        //3 个文本框
        TextField num1 = new TextField(10);
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(20);
        //1 个按钮
        Button button = new Button("=");

        button.addActionListener(new MyCalculatorListener(num1,num2,num3));

        //1 个标签
        Label label = new Label("+");

        //布局
        setLayout(new FlowLayout());

        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);

    }
}

//监听器类
class MyCalculatorListener implements ActionListener{

    //获取三个变量
    private TextField num1,num2,num3;

    public MyCalculatorListener(TextField num1,TextField num2,TextField num3){
        this.num1=num1;
        this.num2=num2;
        this.num3=num3;
    }


    public void actionPerformed(ActionEvent e){
        //1.获得加数和被加数
         int n1=Integer.parseInt(num1.getText());
         int n2=Integer.parseInt(num2.getText());

        //2、将这个值+法运算后,放到第三个框
        num3.setText(""+(n1+n2));

        //3、清除前两个框
        num1.setText("");
        num2.setText("");
    }
}

完全改造为面向对象写法

public class TestCalc2 {
    public static void main(String[] args) {
        new Calculator2().loadFrame();
    }
}
//计算器类
class Calculator2 extends Frame{
    //属性
    TextField num1,num2,num3;

    //方法
    public void loadFrame(){
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(20);

        Button button = new Button("=");
        Label label = new Label("+");
        button.addActionListener(new MyCalculatorListener2(this));

        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }
}

//监听器类
class MyCalculatorListener2 implements ActionListener{

    //获取计算器这个对象,在一个类中组合另外一个类
    Calculator2 calculator = null;

    public MyCalculatorListener2(Calculator2 calculator){
        this.calculator=calculator;
    }

    public void actionPerformed(ActionEvent e){
        //1、获取加数和被加数
        //2、将这个值 + 法运算后,放到第三个框
        //3、清除前两个框

        int n1=Integer.parseInt(calculator.num1.getText());
        int n2=Integer.parseInt(calculator.num2.getText());
        calculator.num3.setText(""+(n1+n2));
        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}

内部类:

  • 更好的包装
public class TestCalc2 {
    public static void main(String[] args) {
        new Calculator2().loadFrame();
    }
}
//计算器类
class Calculator2 extends Frame{
    //属性
    TextField num1,num2,num3;

    //方法
    public void loadFrame(){
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(20);

        Button button = new Button("=");
        Label label = new Label("+");
        button.addActionListener(new MyCalculatorListener2());

        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }

    //监听器类
    //内部类最大的好处,就是畅通无阻的访问外部类
    private class MyCalculatorListener2 implements ActionListener{

        public void actionPerformed(ActionEvent e){
            //1、获取加数和被加数
            //2、将这个值 + 法运算后,放到第三个框
            //3、清除前两个框

            int n1=Integer.parseInt(num1.getText());
            int n2=Integer.parseInt(num2.getText());
            num3.setText(""+(n1+n2));
            num1.setText("");
            num2.setText("");
        }
    }
}

画笔

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

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

        //g.setColor(Color.green);
        g.fillRect(150,200,200,200);

        //养成习惯,画笔用完,将他还原成最初的颜色
    }
}

注:养成习惯,画笔用完,将他还原成最初的颜色

鼠标监听

目的:想要实现鼠标画画

package com.axiaoleng1;

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

        //鼠标监听器,正对这个窗口
        this.addMouseListener(new MyMouseListener());

        setVisible(true);
    }

    public void paint(Graphics g){
        //画画,监听鼠标的事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point = (Point) iterator.next();
            g.setColor(Color.blue);
            g.fillOval(point.x,point.y,10,10);
        }
    }

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

    //适配器模式  内部类
    private class MyMouseListener extends MouseAdapter {
        //鼠标 按下,弹起,按住不放

        public void mousePressed(MouseEvent e){
           //super.mousePressed(e);
            MyFrame frame = (MyFrame) e.getSource();
            //这个我们点击的时候,就会在界面上产生一个点!
            //这个点就是鼠标的点
            frame.addPaint(new Point(e.getX(),e.getY()));

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

注:有点难,建议多听几遍!!!

窗口监听

package com.axiaoleng1;

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

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

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


        this.addWindowListener(
                //匿名内部类
                new WindowAdapter(){
                    //关闭窗口
                    @Override
                    public void windowClosing(WindowEvent e) {
                        System.out.println("windowClosing");
                        System.exit(0);
                    }
                    //激活窗口
                    @Override
                    public void windowActivated(WindowEvent e) {
                        System.out.println("windowActivated");
                    }
                }
        );
    }

//    class MyWindowListener extends WindowAdapter{
//        public void windowClosing(WindowEvent e){
//            setVisible(false); //隐藏窗口。通过按钮,隐藏当前窗口
//            System.exit(0);//正常退出
//        }
//    }
}

键盘监听

package com.axiaoleng1;

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

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

class KeyFrame extends Frame {
    public KeyFrame(){
        setBounds(1,2,300,400);
        setVisible(true);

        this.addKeyListener(new KeyAdapter() {
            //键盘按下
            @Override
            public void keyPressed(KeyEvent e) {
                //获得键盘下的键是哪一个,当前的码
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);//不需要去记录这个数值,直接使用静态属性 VK_XXX
                if(keyCode==KeyEvent.VK_UP)
                    System.out.println("你按下了上键");
                if(keyCode==KeyEvent.VK_DOWN)
                    System.out.println("你按下了下键");
            }
        });
    }
}

Swing

窗口、面板

package com.axiaoleng2;

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

public class JFrameDemo {
    //init()  初始化
    public void init(){
        //顶级窗口
        JFrame jf = new JFrame();
        jf.setVisible(true);
        jf.setBounds(100,100,200,200);
        jf.setBackground(Color.cyan);

        //设置文字 Jlabel
        JLabel label= new JLabel("欢迎来到狂神说Java系列节目");
        jf.add(label);
        
        //关闭事件
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

标签居中

package com.axiaoleng2;

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

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

class MyJframe2 extends JFrame{
    public void init(){
        this.setVisible(true);
        this.setBounds(10,10,200,200);

        JLabel label= new JLabel("欢迎来到狂神说Java系列节目");
        this.add(label);

        //让文本标签居中    设置水平对齐
        label.setHorizontalAlignment(SwingConstants.CENTER);

        //获得一个容器
        Container container =this.getContentPane();
        container.setBackground(Color.YELLOW);
    }
}

弹窗

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

package com.axiaoleng2;

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

public class DialogDemo extends JFrame {

    public DialogDemo(){
        this.setVisible(true);
        this.setSize(700,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //JFrame 放东西 容器
        Container container = this.getContentPane();
        //绝对布局
        container.setLayout(null);

        //按钮
        JButton button = new JButton("点击弹出一个对话框");
        button.setBounds(30,30,200,50);

        //点击这个按钮的时候,弹出一个弹窗
        button.addActionListener(new ActionListener() { //监听器
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹窗
                new MyDialogDemo();
            }
        });

        container.add(button);
    }

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


//弹窗的窗口
class MyDialogDemo extends JDialog{
    public MyDialogDemo(){
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        //this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

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

        container.add(new Label("秦老师带你学java"));
    }
}

标签

  • label
new JLabel("xxx");
  • 图标ICON
package com.axiaoleng2;

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

//图标,需要实现类,Frame继承
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 container=getContentPane();
        container.add(label);

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

    public static void main(String[] args) {
        new IconDemo().init();
    }
    
    public void paintIcon(Component c,Graphics g,int x,int y){
        g.fillOval(x,y,width,height);
    }
    public int getIconWidth(){
        return this.width;
    }
    public int getIconHeight(){
        return this.height;
    }
}
  • 图片Icon
package com.axiaoleng2;

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

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

    public ImageIconDemo(){
        //获取图片的地址
        //获取当前这个类,class下面同级资源的图片 url具体的地址
        JLabel label=new JLabel("ImageIcon");
        URL url=ImageIconDemo.class.getResource("1.png");

        ImageIcon imageIcon = new ImageIcon(url);//命名不要冲突了
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);

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

        setVisible(true);
        setDefaultCloseOperation(SwingConstants.CENTER);
        setBounds(100,100,200,200);
    }
}

面板

  • JPanel
package com.axiaoleng2;

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

public class JPanelDemo extends JFrame {
    public static void main(String[] args) {
        new JPanelDemo();
    }
    public JPanelDemo(){
        Container container = this.getContentPane();
        //后面的参数的意思,间距
        container.setLayout(new GridLayout(2,1,10,10));

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

        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        container.add(panel1);

        this.setVisible(true);
        this.setSize(500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • JScollPane 滚动条
package com.axiaoleng2;

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

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

        //文本域
        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("欢迎学习狂神说java");

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


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

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

按钮

  • 图片按钮
package com.axiaoleng2;

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

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

    public JButtonDemo01(){
        Container container=this.getContentPane(); //获得一个容器
        //将一个图片变成图标
        URL resource = JButtonDemo01.class.getResource("1.png");//获得当前路径下的资源
        Icon icon = new ImageIcon(resource);

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


        //add
        container.add(button);

        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 单选按钮
package com.axiaoleng2;

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

public class JButtonDemo02 extends JFrame {
    public JButtonDemo02(){
        Container container=this.getContentPane(); //获得一个容器
        //将一个图片变成图标
        URL resource = JButtonDemo01.class.getResource("1.png");//获得当前路径下的资源
        Icon icon = new ImageIcon(resource);

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

        //由于单选框只能选择一个,分组,一个组中只能选一个
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        group.add(radioButton3);

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

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

    public static void main(String[] args) {
        new JButtonDemo02();
    }
}
  • 复选按钮
package com.axiaoleng2;

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

public class JButtonDemo03 extends JFrame {
    public JButtonDemo03(){
        Container container=this.getContentPane(); //获得一个容器
        //将一个图片变成图标
        URL resource = JButtonDemo01.class.getResource("1.png");//获得当前路径下的资源
        Icon icon = new ImageIcon(resource);

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

        container.add(checkBox01,BorderLayout.NORTH);
        container.add(checkBox02,BorderLayout.SOUTH);

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

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

列表

  • 下拉框
package com.axiaoleng3;

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

public class TestComboxDemo01 extends JFrame {
    public TestComboxDemo01(){

        Container container = this.getContentPane();

        JComboBox status = new JComboBox();

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

        container.add(status);


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

    public static void main(String[] args) {
        new TestComboxDemo01();
    }
}
  • 列表框
package com.axiaoleng3;

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

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

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

        //生成列表的内容
        //String[] contents = {"1","2","3"};
        Vector contents=new Vector();
        //列表中需要放入内容
        JList jList=new JList(contents);
        
        contents.add("zhansan");
        contents.add("lisi");
        contents.add("wangwu");

        container.add(jList);
        
        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 应用场景
    选择地区,或者一些单个选项
    列表,展示信息,一般是动态扩容

文本框

  • 文本框
package com.axiaoleng3;

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

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


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

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

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

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

密码框

package com.axiaoleng3;

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

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

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

        container.add(passwordField);

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

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

文本域

package com.axiaoleng2;

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

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

        //文本域
        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("欢迎学习狂神说java");

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


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

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

贪吃蛇

帧,如果时间片足够小,就是动画,一秒30帧,连起来是动画,拆开是静态的图片
键盘监听
定时器 Timer
1、定义数据
2、画上去
3、监听事件
键盘
事件

package com.snake;

import javax.swing.*;

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

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

        frame.setVisible(true);
        frame.setResizable(false);  //窗口大小不可变
        frame.setBounds(10,10,900,720);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
package com.snake;


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

//数据中心
public class Data {

    //相对路径 tx。png
    //绝对路径 / 相当于当前的项目
    private static URL headerURL = Data.class.getResource("statics/header.png");
    private static URL upURL = Data.class.getResource("statics/up.png");
    private static URL downURL = Data.class.getResource("statics/down.png");
    private static URL leftURL = Data.class.getResource("statics/left.png");
    private static URL rightURL = Data.class.getResource("statics/right.png");
    private static URL bodyURL = Data.class.getResource("statics/body.png");
    private static URL foodURL = Data.class.getResource("statics/food.png");

    public static ImageIcon header = new ImageIcon(headerURL);
    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 ImageIcon body = new ImageIcon(bodyURL);
    public static ImageIcon food = new ImageIcon(foodURL);
}
package com.snake;

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

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

    //定义蛇的数据结构
    int length;  //蛇的长度
    int[] snakeX = new int[1000]; //蛇的x坐标
    int[] snakeY = new int[1000]; //蛇的y坐标
    String fx;

    //食物的坐标
    int foodx;
    int foody;
    Random random =  new Random();

    int score; //成绩


    //游戏当前的状态:开始,停止
    boolean isStart = false;//默认是不开始

    boolean isFail = false; //游戏失败状态

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

    //构造器
    public GamePanel(){
        init();
        //获得焦点和键盘事件
        this.setFocusable(true); //获得焦点事件
        this.addKeyListener(this);  //获得键盘监听事件
        timer.start(); //游戏开始定时器启动
    }

    //初始化方法
    public void init(){
        length=3;
        snakeX[0]=145;snakeY[0]=100;  //脑袋的坐标
        snakeX[1]=85;snakeY[1]=100;   //第一个身体的坐标
        snakeX[2]=25;snakeY[2]=100;   //第二个身体的坐标
        fx="R"; //初始化方向向右

        //把食物随机的放在界面上
        foodx = 25+25*random.nextInt(34);
        foody = 75+25*random.nextInt(24);

        score=0;
    }

    //绘制面板,我们游戏中的所有东西,都是用这个画笔来画
    protected void paintComponent(Graphics g){
        super.paintComponent(g);//清屏

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

        //画积分
        g.setColor(Color.blue);
        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));
            g.drawString("按下空格开始游戏",300,300);
        }

        if(isFail){
            g.setColor(Color.red);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("失败,按下空格重新开始",300,300);
        }
    }
    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();  //获得键盘按键是哪一个
        if(keyCode==KeyEvent.VK_SPACE){  //如果按下的是空格键
            if(isFail){
                //重新开始
                isFail=false;
                init();
            }else {
                isStart = !isStart; //取反
            }
            repaint();
        }
        //小蛇移动
        if(keyCode == KeyEvent.VK_UP){
            fx="U";
        }else if(keyCode == KeyEvent.VK_DOWN){
            fx="D";
        }else if(keyCode == KeyEvent.VK_RIGHT){
            fx="R";
        }else if(keyCode == KeyEvent.VK_LEFT){
            fx="L";
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {
    }
    @Override
    public void keyTyped(KeyEvent e) {
    }

    //事件监听---需要通过固定事件来刷新,1s=10次
    @Override
    public void actionPerformed(ActionEvent e) {
        if(isStart &&isFail==false){ //如果游戏是开始状态,就让小蛇动起来

            //吃食物
            if(snakeX[0]==foodx && snakeY[0]==foody){
                length=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] + 60;
                //边界判断
                if(snakeX[0]>1000){snakeX[0]=25;}
            }else if(fx.equals("L")){
                snakeX[0]=snakeX[0]-60;
                if(snakeX[0]<25){snakeX[0]=1000;}
            }else if(fx.equals("U")){
                snakeY[0]=snakeY[0]-60;
                if(snakeY[0]<75){snakeY[0]=650;}
            }else if(fx.equals("D")){
                snakeY[0]=snakeY[0]+60;
                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();//定时器开始
    }
}

在这里插入图片描述
结果:可以运行,没有报错,但吃不到东西,不能增加长度。
原因:我仔细想了一些,也对照了代码,可能是图片的大小不符合到处,贪吃蛇的头的坐标与食物的坐标不相同,无法执行。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值