❤️《GUI编程从入门到精通》(建议收藏)❤️

GUI编程(+贪吃蛇示例代码)


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

1.简介


GUI的核心技术:Swing AWT

​ 1.界面不美观,

​ 2.需要jre环境!

  • 可以写出自己心中想要的小工具

  • 工作的时候,也可能需要维护到Swing界面,概率极小!

  • 了解MVC架构,了解监听!

2、AWT


2.1、AWT介绍

1.new 类!

2.包含了很多类和接口!

3.用于GUI编程图像用户界面

4.元素:窗口、按钮、文本框

5.java.awt包

2.2、组件和容器

2.3、Frame

package Demo01;

import java.awt.*;

//GUI的第一个界面
public class TestFrame {
    
    
    public static void main(String[] args) {
    
    
        //Frame 对象  JDK 看源码!
        Frame frame = new Frame("我的第一个Java图形界面窗口");

        //需要设置可见性  有weight 和height
        frame.setVisible(true);

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

        //设置窗口背景颜色  Color
        frame.setBackground(new Color(104, 243, 22));

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

        //设置大小固定setResizable默认位true 也就是可以改变窗口大小
        frame.setResizable(false);


    }
}

==问题:发现窗口关闭不了,停止Java运行即可

多个窗口代码示例:

package Demo01;

import java.awt.*;

public class TestFrame2 {
    
    
    public static void main(String[] args) {
    
    
        //展示多个窗口 new
        MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.blue);
        MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.red);
        MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.green);
        MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.yellow);
    }
}
 class MyFrame extends Frame{
    
    
    static int 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.4、面板(Panel)

==解决了关闭事件

package Demo01;

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

//面板 Panel  可以看成是一个空间,但是不能单独存在
public class TestPanel {
    
    
    public static void main(String[] args) {
    
    
        Frame frame = new Frame();
        //布局的概念
        Panel panel = new Panel();
        Panel panel2 = new Panel();

        //设置布局
        frame.setLayout(null);
        //坐标
        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(55, 238, 238, 255));
        //panel 设置坐标  相对于frame
        panel.setBounds(10,10,100,400);
        panel.setBackground(new Color(0, 255, 135, 255));
        panel2.setBounds(100,100,300,400);
        panel2.setBackground(new Color(232, 17, 17, 255));

        //frame.add(panel)
        frame.add(panel);
        frame.add(panel2);
        frame.setVisible(true);

        //监听事件,监听窗口关闭事件 System.exit(0)
        //适配器模式:
        frame.addWindowListener(new WindowListener() {
    
    
            @Override
            public void windowOpened(WindowEvent e) {
    
    

            }

            //窗口关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
    
    
                //结束程序
                System.exit(0);

            }

            @Override
            public void windowClosed(WindowEvent e) {
    
    

            }

            @Override
            public void windowIconified(WindowEvent e) {
    
    

            }

            @Override
            public void windowDeiconified(WindowEvent e) {
    
    

            }

            @Override
            public void windowActivated(WindowEvent e) {
    
    

            }

            @Override
            public void windowDeactivated(WindowEvent e) {
    
    

            }
        });
    }
}

2.5、布局管理器

  • 流式布局

代码示例:

package Demo01;

import java.awt.*;

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

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

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

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

        frame.setVisible(true);
    }
}
  • 东西南北中

代码示例:

package Demo01;

import java.awt.*;

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,BorderLayout.EAST);
        frame.add(west,BorderLayout.WEST);
        frame.add(south,BorderLayout.SOUTH);
        frame.add(north,BorderLayout.NORTH);
        frame.add(center,BorderLayout.CENTER);

        frame.setSize(400,400);
        frame.setVisible(true);
    }
}
  • 表格式布局

代码示例:

package Demo01;
import java.awt.*;
public class TestGridLayout {
    
    
    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);

    }
}

三种布局结合

代码示例:

package Demo01;

import java.awt.*;

public class ExDmoe {
    
    
    public static void main(String[] args) {
    
    
        //总的Frame
        Frame frame = new Frame("Ex");
        frame.setLayout(new GridLayout(2,1));
        frame.setSize(400,400);
        frame.setLocation(300,300);
        frame.setBackground(Color.BLACK);
        frame.setVisible(true);

        //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);
        //中间的四个
        for (int i = 0; i < 4; i++) {
    
    
            p4.add(new Button("for-"+i));
        }
        p3.add(p4,BorderLayout.CENTER);

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

    }
}

总结:

  • Frame是一个顶级窗口
  • Panel 无法单独显示,必须添加到某个容器中
  • 布局管理器
    • 流式布局
    • 东西南北中
    • 表格式布局

2.6、事件监听

代码示例:

package Demo01;

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

public class TestActionEvent {
    
    
    public static void main(String[] args) {
    
    
        //按下按钮,触发一些事件
        Frame frame=new Frame();
        Button button = new Button();

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

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

        WindownClose(frame);//调用关闭窗口

    }
    //关闭窗口事件
    private static void  WindownClose( Frame frame){
    
    
        frame.addWindowListener(new WindowListener() {
    
    
            @Override
            public void windowOpened(WindowEvent e) {
    
    

            }
            @Override
           public void windowClosing(WindowEvent e) {
    
    
                 System.exit(0);
            }
           @Override
            public void windowClosed(WindowEvent e) {
    
    

            }

            @Override
            public void windowIconified(WindowEvent e) {
    
    

            }

            @Override
            public void windowDeiconified(WindowEvent e) {
    
    

            }

            @Override
            public void windowActivated(WindowEvent e) {
    
    

            }

            @Override
            public void windowDeactivated(WindowEvent e) {
    
    

            }
        });

    }
}

//事件监听
class  MyActionListener implements ActionListener {
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
    
    
        System.out.println("你好呀!");
    }
}

示例2:多个按钮共享一个事件

package Demo01;

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 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{
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
    
    
        //e.getActionCommand()获取按钮上的信息
        System.out.println("按钮被点击了:msg=>"+ e.getActionCommand());
        if(e.getActionCommand().equals("start")){
    
    

        }



    }
}

2.7、输入框TextField 监听

代码示例:

package Demo01;

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

public class TestText01 {
    
    
    public static void main(String[] args) {
    
    
        //main里只管启动
        new MyFrame2();
    }
}

class MyFrame2 extends Frame{
    
    
    public MyFrame2(){
    
    
        TextField textField = new TextField();
        //因为extends Frame 所有Frame可以不用写
        add(textField);
        //监听这个文本框输入的文字
        MyActionListener2 myActionListener2 = new MyActionListener2();
        //按钮下回车就会触发这个输入框的事件
        textField.addActionListener(myActionListener2);
        //设置编码
        textField.setEchoChar('*');//密码框
        setVisible(true);
        pack();
    }
}

class MyActionListener2 implements ActionListener{
    
    

    @Override
    public void actionPerformed(ActionEvent e) {
    
    

      TextField field=(TextField)e.getSource();//获得一些资源,返回一个对象
        System.out.println(field.getText());
        field.setText("");  //NULL ""
    }
}

2.8、计算器

示例1:

package Demo01;

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

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; 
    public void actionPerformed(ActionEvent e) {
    
    
        //1.获得加数和被加数
        int n1=  Integer.parseInt(num1.getText());//将字符串类型转换为int类型
        int n2=  Integer.parseInt(num2.getText());
        //2.将这个值加法运算后放入第三个框中
       num3.setText(""+(n1+n2));
  
        //3.清除前两个框的内容
        num1.setText("");
        num2.setText("");


    }
}

优化示例(完全改造面向对象):

package Demo01;

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

public class TestCalc {
    
    
    public static void main(String[] args) {
    
    
        new Calculator().loadFrame();

    }
}
//计算器类
class  Calculator 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 MyCalculatorListener(this));
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }
}

//监听器类
class  MyCalculatorListener implements ActionListener{
    
    
    //获取计算器这个对象,在一个类中组合另外一个类
    Calculator calculator=null;
    public MyCalculatorListener(Calculator calculator){
    
    
        this.calculator=calculator;

    }
    @Override
    public void actionPerformed(ActionEvent e) {
    
    
        //1.获得加数和被加数
        int n1=Integer.parseInt(calculator.num1.getText());
        int n2=Integer.parseInt(calculator.num2.getText());
        //2.将这个值加法运算后放入第三个框中
        calculator.num3.setText(""+(n1+n2));
        //3.清除前两个框的内容
        	calculator.num1.setText("");
        calculator.num2.setText("");




    }
}

内部类:

package Demo01;

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

public class TestCalc {
    
    
    public static void main(String[] args) {
    
    
        new Calculator().loadFrame();

    }
}
//计算器类
class  Calculator 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 MyCalculatorListener());
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }
    //监听器类
    //内部类最大的好处就是可以畅通无阻的访问外部的属性和方法
 private  class  MyCalculatorListener implements ActionListener{
    
    
            @Override
            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("");
            }
        }
    }

2.9、画笔

代码示例:

package Demo02;

import java.awt.*;

public class TestPanit {
    
    
    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(Color.red);
        //g.drawOval(100,100,100,100);
        g.fillOval(100,100,100,100);//实心圆
       // g.setColor(Color.green);
        g.fillRect(150,150,100,100);

        //画笔用完,还原到最初的颜色
    }
}

2.1.0、鼠标监听

目的:实现鼠标画点

代码示例:

package Demo02;

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, 400);

        //存储鼠标点击的点
        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.red);
            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.1.1、窗口监听

代码示例:

package Demo02;

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

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

    }
}

class WindowFrame extends Frame {
    
    
    public WindowFrame() {
    
    
        setBounds(100, 100, 200, 200);
        setBackground(Color.GREEN);
        setVisible(true);
        //addWindowListener(new MyWindownListener());
        this.addWindowListener(
                //匿名内部类
                new WindowAdapter() {
    
    
                    @Override
                    public void windowOpened(WindowEvent e) {
    
    
                        System.out.println("windowOpened");
                    }

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

                    @Override
                    public void windowClosed(WindowEvent e) {
    
    
                        System.out.println("windowClosed");
                    }

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

                }
        );

    }
    class  MyWindowListener implements WindowListener{
    
    
        @Override
        public void windowOpened(WindowEvent e) {
    
    

        }

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

        @Override
        public void windowClosed(WindowEvent e) {
    
    

        }

        @Override
        public void windowIconified(WindowEvent e) {
    
    

        }

        @Override
        public void windowDeiconified(WindowEvent e) {
    
    

        }

        @Override
        public void windowActivated(WindowEvent e) {
    
    

        }

        @Override
        public void windowDeactivated(WindowEvent e) {
    
    

        }
    }
}

2.1.2、键盘监听

代码示例:

package Demo02;
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(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("你按下了上键");
                }
                //根据按下的键,产生不同的结果
            }
        });
    }
}

3、Swing


3.1、窗口

窗口代码示例:

package Demo03;

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.setBounds(100,100,200,200);
        this.setVisible(true);
        JLabel label = new JLabel("欢迎学习Java");
        this.add(label);
        //让文本标签居中  设置水平对齐
        label.setHorizontalAlignment(SwingConstants.CENTER);
        //获得一个容器
        Container content = this.getContentPane();
        content.setBackground(Color.cyan);
    }
}

弹窗代码示例:

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

package Demo03;

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

            }
        });

        container.add(button);

    }

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

    }
}


//弹窗的窗口
class MyDailogDemo extends JDialog{
    
    
    public MyDailogDemo() {
    
    
        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!"));

    }
}

3.2、标签

Label

  • new Label(“xxx”);

图标ICON

代码示例:

package Demo03;

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("tx.png");
        ImageIcon imageIcon = new ImageIcon(url);//命名不要重复
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);

        Container container = getContentPane();
        container.add(label);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,200,200);


    }

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

3.4、面板

JPanel

代码示例:

package Demo04;

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

public class JPanelDemo extends JFrame {
    
    
    public JPanelDemo(){
    
    
        //所有的东西放在container里边
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));//后面参数的意思是间距

        JPanel panel1 = new JPanel(new GridLayout(1,3));
        JPanel panel2 = new JPanel(new GridLayout(1,2));
        JPanel panel3 = new JPanel(new GridLayout(2,1));
        JPanel panel4 = new JPanel(new GridLayout(3,2));

        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel2.add(new JButton("2"));
        panel2.add(new JButton("2"));
        panel3.add(new JButton("3"));
        panel3.add(new JButton("3"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        container.add(panel1);
        container.add(panel2);
        container.add(panel3);
        container.add(panel4);

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


    }

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

    }
}

JScrollPanel

代码示例:

package Demo04;

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

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

        //文本域
        JTextArea textArea=new JTextArea(20,20);
        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();
    }
}

3.5、按钮

  • 图片按钮

代码示例:

package Demo04;

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

public class JButtonDemo extends JFrame {
    
    
    public JButtonDemo(){
    
    
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL resource = JButtonDemo.class.getResource("tx.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);


    }

    public static void main(String[] args) {
    
    

        new JButtonDemo();
    }
}
  • 单选按钮

代码示例:

package Demo04;

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

public class JButtonDemo02 extends JFrame {
    
    
    public JButtonDemo02(){
    
    
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL resource = JButtonDemo.class.getResource("tx.png");
        Icon icon = new ImageIcon(resource);

        //单选框
        JRadioButton radiobutton01 = new JRadioButton("单选框1");
        JRadioButton radiobutton02 = new JRadioButton("单选框2");
        JRadioButton radiobutton03 = new JRadioButton("单选框3");
        //由于单选框只能选择一个,需要分组---一个组中只能选择一个
        ButtonGroup ground = new ButtonGroup();
        ground.add(radiobutton01);
        ground.add(radiobutton02);
        ground.add(radiobutton03);

        container.add(radiobutton01,BorderLayout.CENTER);
        container.add(radiobutton02,BorderLayout.NORTH);
        container.add(radiobutton03,BorderLayout.SOUTH);



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


    }

    public static void main(String[] args) {
    
    

        new JButtonDemo02();
    }
}
  • 多选按钮

代码示例:

package Demo04;

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

public class JButtonDemo03 extends JFrame {
    
    
    public JButtonDemo03(){
    
    
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL resource = JButtonDemo.class.getResource("tx.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();
    }
}

3.6、列表

  • 下拉框

代码示例:

package Demo05;

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

public class TestComboboxDemo01 extends JFrame {
    
    
    public TestComboboxDemo01(){
    
    
        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(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

代码示例:

package Demo05;

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

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

        //生成列表内容
       //String[] contents={"1","2","3"};

        Vector contents = new Vector();
        //列表中需要放入内容
        JList jList = new JList(contents);

        contents.add("1");
        contents.add("2");
        contents.add("3");

        container.add(jList);


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

    }

    public static void main(String[] args) {
    
    
        new TestComboboxDemo02();
    }
}
  • 应用场景:
    • 选择地区或者一些单个选项
    • 列表,展示信息,一般是动态内容

3.7、文本框

  • 文本框

代码示例:

package Demo05;

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

public class TestTextDemo01  extends JFrame {
    
    
    public  TestTextDemo01 (){
    
    
        Container container = this.getContentPane();
        //container.setLayout(null);//绝对布局

        JTextField textField = new JTextField("hellow");
        JTextField textField2 = new JTextField("world",20);

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


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

    }

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

代码示例:

package Demo05;

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,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
    
    
        new  TestTextDemo02 ();
    }
}
  • 文本域

代码示例:

package Demo04;

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

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

        //文本域
        JTextArea textArea=new JTextArea(20,20);
        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();
    }
}

4、 贪吃蛇案例


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

键盘监听

定时器Timer


代码1:

package snake;

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.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //正常游戏界面都应该在面板上!!!
        frame.add(new GamePanel());

    }
}

代码2:

package snake;

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

//数据中心
public class Data {
    
    
    //相对路径   tx.png
    //绝对路径  /(这个/相当于当前的项目)
    public static URL headerURL=Data.class.getResource("static/header.png");
    public static URL upURL=Data.class.getResource("static/up.png");
    public static URL downURL=Data.class.getResource("static/down.png");
    public static URL leftURL=Data.class.getResource("static/left.png");
    public static URL rightURL=Data.class.getResource("static/right.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 URL bodyURL=Data.class.getResource("static/body.png");
    public static ImageIcon body=new ImageIcon(bodyURL);
    
    public static URL foodURL=Data.class.getResource("static/food.png");
    public static ImageIcon food=new ImageIcon(foodURL);

}

代码3:

package 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 lenght; //蛇的长度
    int[]  snakeX=new int[600];//蛇的x坐标25*25
    int[]  snakeY=new int[500];//蛇的y坐标25*25
    String fx="R";//初始方向  向右

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

    int score;//成绩

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

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

    //定时器 以毫秒为单位 1000ms=1s
    Timer timer=new Timer(80,this);//监听这个对象,80毫秒执行一次
    //构造器
    public GamePanel(){
    
    
        init();
        
        //获得焦点和键盘事件
        this.setFocusable(true);//获得焦点事件
        this.addKeyListener(this);//获得键盘监听事件
        timer.start();//游戏一开启,定时器就启动
    }

    //初始化方法
    public void init(){
    
    
        lenght=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); //800/25=34
        foody=75+25*random.nextInt(24);  //600/25=24

        //初始分数
        score=0;

    }


    //绘制面板,我们游戏中的所有东西都使用这个画笔来画
    @Override
    protected void paintComponent(Graphics g) {
    
    
        super.paintComponent(g);  //清屏
        this.setBackground(Color.WHITE);
        //绘制静态面板
        Data.header.paintIcon(this,g,100,10);//头部广告栏
       
        g.fillRect(25,75,850,600);  //默认游戏界面
       
   
        //画积分
        g.setColor(Color.red);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度:"+lenght,750,35);
        g.drawString("分数:"+score,750,50);


        //画食物
        Data.food.paintIcon(this,g,foodx,foody);
         //将小蛇画上去,画到当前面板上--用g这只笔画--画到x,y
        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 < lenght; i++) {
    
    
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//第i个身体坐标
        }

        //游戏状态
        if(!isStart){
    
    
            g.setColor(Color.WHITE);
            
            //设置字体
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("按下空格开始游戏",300,300);
        }


        if (isFail) {
    
    
            g.setColor(Color.RED);
            //设置字体
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("游戏失败,按下空格重新开始!",300,300);
        }
    }


    @Override
    public void keyTyped(KeyEvent e) {
    
    

    }
    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
    
    
        int keyCode = e.getKeyCode();//键盘按键是哪一个
        if(keyCode==KeyEvent.VK_SPACE){
    
     //如果按下的是空格键
         if (isFail){
    
    
            isFail=false; //则重新开始
             init();
         }else{
    
    
            isStart=!isStart; //取反
         }
         repaint();
        }
        //小蛇移动
        if (keyCode==KeyEvent.VK_UP){
    
    
            fx="U";
        }else if(keyCode==KeyEvent.VK_DOWN){
    
    
            fx="D";
        }else if(keyCode==KeyEvent.VK_LEFT){
    
    
            fx="L";
        }else if(keyCode==KeyEvent.VK_RIGHT){
    
    
            fx="R";
        }

    }
    @Override
    public void keyReleased(KeyEvent e) {
    
    

    }

    //事件监听--需要通过固定的时间来刷新,如1s10次
    @Override
    public void actionPerformed(ActionEvent e) {
    
    
         if (isStart&&isFail==false ){
    
    //如果游戏是开始状态,就让小蛇动起来
             //吃食物
             if (snakeX[0]==foodx&&snakeY[0]==foody){
    
    
                 lenght++;//长度加1
                 //分数+10
                 score+=10;
                 //再次出现随机食物
                 foodx=25+25*random.nextInt(34); //800/25=34
                 foody=75+25*random.nextInt(24);  //600/25=24
             }

             
             //移动
             for (int i = lenght-1; i > 0; i--) {
    
    //后一项一到前一项的位置
                 snakeX[i]=snakeX[i-1];
                 snakeY[i]=snakeY[i-1];
             }
             //走向
             if(fx.equals("R")){
    
    
                 snakeX[0]=snakeX[0]+25;
                 if(snakeX[0]>850){
    
     snakeX[0]=25;} //边界判断
             }else if(fx.equals("L")){
    
    
                 snakeX[0]=snakeX[0]-25;
                 if(snakeX[0]<25){
    
     snakeX[0]=850;} //边界判断
             }else if(fx.equals("U")){
    
    
                 snakeY[0]=snakeY[0]-25;
                 if(snakeY[0]<75){
    
     snakeY[0]=650;} //边界判断
             } else if(fx.equals("D")){
    
    
                 snakeY[0]=snakeY[0]+25;
                 if(snakeY[0]>650){
    
     snakeY[0]=75;} //边界判断
             }

             //失败判定。撞到自己即失败
             for (int i = 1; i < lenght; i++) {
    
    
                 if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]) {
    
    
                     isFail=true;
                 }
             }


             repaint(); //重新绘制页面
         }
         timer.start();  //定时器开启
    }
}

//键盘监听器

猜你喜欢

转载自blog.csdn.net/weixin_50569789/article/details/116401360