Java_GUI编程

组件

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

1、简介

GUI的核心技术:Swing AWT
1.因为界面不美观
2.需要jre环境
为什么要学习GUI?
学习MVC架构思想
1、可以写出自己心中想要的小工具
2、工作的时候,也可能需要维护到Swing界面,概率极小
3、了解MVC架构,了解监听!

2、AWT

2.1、AWT介绍

Abstract Windowing Toolkit 抽象窗口工具包
包含了很多类和接口!GUI:图形用户界面
image
1、Frame窗口组件:

package com.java.oop.GUI;
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(400,400);
        //设置背景颜色 Color
        frame.setBackground(new Color(150, 27, 32));
        //弹出的初识位置
        frame.setLocation(200,200);
	//设置大小固定
	frame.setResizable(false);
    }
}

多个窗口:

package com.java.oop.GUI;

import java.awt.*;

public class TestFrameTwo {
    public static void main(String[] args) {
        //展示多个窗口
        MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.black);
        MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.yellow);
        MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.red);
        MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.magenta);
    }
}
//封装
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、Panel面板组件:

package com.java.oop.GUI;

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(40,161,35));
        //panel设置坐标,相对于frame
        panel.setBounds(50,50,400,400);
        panel.setBackground(new Color(193,15,60));
        //将panel添加到frame中
        frame.add(panel);
        //设置窗口可见性
        frame.setVisible(true);
        //监听事件,监听窗口关闭事件 System.exit(0),
        // 因为WindowListener是一个接口,需要重写里面的所有方法,所以采用适配器模式
        //WindowAdapter是一个抽象方法,实现了WindowListener接口
        frame.addWindowListener(new WindowAdapter(){
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }
}

3、布局管理器
流式布局(FlowLayout)

package com.java.oop.GUI;

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

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");
        Button button4 = new Button("button4");

        //改为流式布局
        frame.setLayout(new FlowLayout());
        frame.setSize(200,200);
        //把按钮增加上去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);

        frame.setVisible(true);

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

东西南北中(BorderLayout)

package com.java.oop.GUI;

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

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

        //东西南北中BorderLayout布局
        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);

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

表格布局(GridLayout)

package com.java.oop.GUI;

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

public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestGridLayout");
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");
        Button button6 = new Button("button6");

        //设置为表格布局
        frame.setLayout(new GridLayout(3,2));
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);

        frame.pack();//Java函数,自适应大小
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter(){
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }
}

布局练习题:

package com.java.oop.GUI;

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

public class TestLayout {
    public static void main(String[] args) {
        //1.分解图形:1个Frame,4个Panel
        Frame frame = new Frame("布局练习");
        frame.setSize(400,300);
        frame.setLocation(400,300);

        //2.外层采用GridLayout布局,中间采用表格布局BorderLayout
        frame.setLayout(new GridLayout(2,1));
        frame.setVisible(true);
        //布局
        Panel panel1 = new Panel(new BorderLayout());
        Panel panel2 = new Panel(new GridLayout(2,1));
        Panel panel3 = new Panel(new BorderLayout());
        Panel panel4 = new Panel(new GridLayout(2,2));
        //添加上面一层
        panel1.add(new Button("East-1"),BorderLayout.EAST);
        panel1.add(new Button("West-1"),BorderLayout.WEST);
        panel2.add(new Button("p2-btn-1"));
        panel2.add(new Button("p2-btn-2"));
        panel1.add(panel2,BorderLayout.CENTER);
        //添加下面一层
        panel3.add(new Button("East-2"),BorderLayout.EAST);
        panel3.add(new Button("West-2"),BorderLayout.WEST);

        //中间4个Button
        for (int i = 0; i < 4; i++) {
            panel4.add(new Button("for-"+i));
        }
        panel3.add(panel4,BorderLayout.CENTER);

        frame.add(panel1);
        frame.add(panel3);

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

总结:
1.Frame是一个顶级窗口
2.Panel无法单独显示,必须添加到某个容器中
3.布局管理器

  • 流式(FlowLayout)
  • 东西南北中(BorderLayout)
  • 表格(GridLayout)

4.大小、定位,背景颜色、可见性、监听

动作事件:

package com.java.oop.GUI;

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

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

        //因为addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
        MyActionListner myActionListner = new MyActionListner();
        button.addActionListener(myActionListner);

        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 MyActionListner implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("nihao");
    }
}

两个按钮实现同一个监听:

package com.java.oop.GUI;

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 TestActionTwo {
    public static void main(String[] args) {
        //两个按钮,实现同一个监听
        Frame frame = new Frame("开始-停止");
        Button start = new Button("start");
        Button stop = new Button("stop");

        frame.add(start,BorderLayout.NORTH);
        frame.add(stop,BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
	//可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值
        //可以多个按钮只写一个监听类
        stop.setActionCommand("Button2-stop);

        MyMonitor myMonitor = new MyMonitor();

        start.addActionListener(myMonitor);
        stop.addActionListener(myMonitor);
        
        frame.addWindowListener(new WindowAdapter(){
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }
}

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

5、输入框TextField

package com.java.oop.GUI;

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 TestTextField {
    public static void main(String[] args) {
        //启动
        MyFrameText myFrameText = new MyFrameText();
        myFrameText.addWindowListener(new WindowAdapter(){
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }

    }

class MyFrameText extends Frame {
        public MyFrameText(){
            TextField textField = new TextField();
            add(textField);
            //监听这个文本框输入的文字
            MyActionListenerText myActionListenerText = new MyActionListenerText();
            textField.addActionListener(myActionListenerText);

            pack();
            setVisible(true);

        }
}

class MyActionListenerText implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {

        TextField field = (TextField)e.getSource();//获得一些资源,返回的一个对象
        System.out.println(field.getText());//获得输入框的文本
    }
}

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

oop原则:组合,大于继承,优先使用组合

class A extends B {
    
}

class A{
    public B b;
}

package gui;

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

//简易计算器
public class TestCalculate {
    public static void main(String[] args) {
        Calculate calculate = new Calculate();
    }
}

//计算器类
class Calculate extends Frame{
    public Calculate(){
        //3个文本框
        TextField num1 = new TextField(10);//字符数
        TextField num2 = new TextField(10);//字符数
        TextField num3 = new TextField(20);//字符数
        //1个按钮
        Button button = new Button("=");
        //1个标签
        Label label = new Label("+");
        button.addActionListener(new MyCalculatorListener(num1,num2,num3));

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

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

        pack();
        setVisible(true);

    }
}

//监听器类
class MyCalculatorListener implements ActionListener{
    //获取计算器这个对象,在一个类中组合另外一个类;
    /*Calculate calculate = null;
    public MyCalculatorListener(Calculate calculate) {
        this.calculate = calculate;
    }*/
    //获取三个变量
    private TextField num1,num2,num3;
    public MyCalculatorListener(TextField num1,TextField num2,TextField num3) {
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }
    @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("");
    }
}

完全改造为面向对象写法:组合

package src.gui;

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

//面向对象的写法
public class TestCalc2 {
    //简易计算器
    public static void main(String[] args) {
        Calculate calculate = new Calculate();
        calculate.loadFrame();
    }
}
    //计算器类
    class Calculate extends Frame {
        //属性
        TextField num1, num2, num3;
        //方法
        public void loadFrame() {
            //3个文本框
            num1 = new TextField(10);//字符数
            num2 = new TextField(10);//字符数
            num3 = new TextField(20);//字符数
            //1个按钮
            Button button = new Button("=");
            //1个标签
            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 {
        //获取计算器这个对象,在一个类中组合另外一个类;
        Calculate calculate = null;

        //获取三个变量
        public MyCalculatorListener(Calculate calculate) {
            this.calculate = calculate;
        }

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

            //2.将这个值 + 法运算后,放到第三个框
            calculate.num3.setText("" + (n1 + n2));
            //3.清楚前两个框
            calculate.num1.setText("");
            calculate.num2.setText("");
        }
    }

内部类:更好的包装

package src.gui;

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

//面向对象的写法
public class TestCalc2 {
    //简易计算器
    public static void main(String[] args) {
        Calculate calculate = new Calculate();
        calculate.loadFrame();
    }
}
    //计算器类
    class Calculate extends Frame {
        //属性
        TextField num1, num2, num3;
        //方法
        public void loadFrame() {
            //3个文本框
            num1 = new TextField(10);//字符数
            num2 = new TextField(10);//字符数
            num3 = new TextField(20);//字符数
            //1个按钮
            Button button = new Button("=");
            //1个标签
            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("");
            }
        }
    }

画笔:pain

package src.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,500);
        setVisible(true);
    }
    //画笔

    @Override
    public void paint(Graphics g) {
        //画笔,需要有颜色,画笔可以画画
        g.setColor(Color.red);
        g.drawOval(100,100,100,100);
        g.fillRect(150,200,200,200);
        //养成习惯,画笔用完,将他还原到最初的颜色
    }
}

2.8、鼠标监听


目的:实现鼠标画画

package src.mouse;

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

//鼠标监听事件
public class TestMouseListener {
    public static void main(String[] args) {
        MyFrame myFrame  = new MyFrame("画图");
        myFrame.setVisible(true);
    }
}

//自己的类
class MyFrame extends Frame{
    //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
    ArrayList points;
    public MyFrame(String title) throws HeadlessException {
        super(title);

        setBounds(200,200,400,200);
        //存储鼠标的点
        points = new ArrayList<>();
        //鼠标监听器,正对这个窗口
        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 addPoint(Point point){
        points.add(point);
    }

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

        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame fram = (MyFrame)e.getSource();
            //这个我们点击的时候,就会在界面上产生一个点!画
            //这个点就是鼠标的点
            fram.addPoint(new Point(e.getX(),e.getY()));
            //每次点击鼠标都需要重新画一遍
            fram.repaint();//刷新
        }
    }
}

2.9、窗口监听

package src.window;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//窗口监听事件
public class TestWindowListener {
    public static void main(String[] args) {
        new MyWindowFrame();
    }
}

class MyWindowFrame extends Frame{
    public MyWindowFrame() {
        setBounds(100,100,200,200);
        setBackground(Color.red);
        setVisible(true);
        //匿名内部类
        addWindowListener(new WindowAdapter() {
            //关闭窗口
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
                System.exit(0);//正常退出
            }
            //激活窗口
            @Override
            public void windowActivated(WindowEvent e) {
                MyWindowFrame source = (MyWindowFrame)e.getSource();
                source.setTitle("被激活了");
                System.out.println("windowActivated");
            }
        });
    }
}

2.10、键盘监听

package src.KeyListener;

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(100,100,300,400);
        setVisible(true);

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

3、Swing

3.1、窗口,面板

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

public class JFrameDemo extends JFrame{
    //init(); 初始化
    public void init(){
        JFrame jf = new JFrame("这是一个JFrame窗口");
        jf.setVisible(true);
        jf.setBounds(100,100,200,200);
        //jf.setBackground(Color.red);
        //JFrame里面设置背景颜色需要先获取容器
        Container container = this.getContentPane();
        container.setBackground(Color.red);

        //设置文字标签
        JLabel jl = new JLabel("Hello,Swing");
        //让文本标签居中,设置水平对齐
        jl.setHorizontalAlignment(SwingConstants.CENTER);
        jf.add(jl);

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

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

3.2、弹窗

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

package src.swing;

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

public class TestJDialog extends JFrame{
    public TestJDialog() {
        this.setVisible(true);
        this.setBounds(100,100,200,200);
        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 TestJDialog();
    }
}

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

        Container container1 = getContentPane();
        container1.setLayout(null);
        container1.setBackground(Color.red);
        JLabel label = new JLabel("Hello,JDialog");
        container1.add(label);
    }
}

3.3、标签

按钮

package src.swing.Icon;

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.width = width;
        this.height = height;
    }

    public void init(){
        IconDemo iconDemo = new IconDemo(15,15);
        //图标放在标签,也可以放在按钮上
        JLabel jLabel = new JLabel("icontest", iconDemo, SwingConstants.CENTER);

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

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

    public static void main(String[] args) {
        new IconDemo().init();
    }
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,height);
    }

    @Override
    public int getIconWidth() {
        return 0;
    }

    @Override
    public int getIconHeight() {
        return 0;
    }
}

图片按钮

package src.swing.Icon;

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

//图片按钮
public class ImageIconDemo extends JFrame{


    public ImageIconDemo() {
        //获取图片地址
        URL url = ImageIconDemo.class.getResource("Mysql外键约束.png");

        ImageIcon imageIcon = new ImageIcon(url);
        JLabel jLabel = new JLabel("ImageIcon");
        jLabel.setIcon(imageIcon);

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

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

    }

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

}

3.4、面板

package src.swing.Icon;

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

public class JPanelDemo extends JFrame {
    public JPanelDemo() {
        Container container = getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));//后面参数的意思是间距

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

        jPanel1.add(new JButton("1"));
        jPanel1.add(new JButton("2"));
        jPanel1.add(new JButton("3"));

        container.add(jPanel1);
        this.setVisible(true);
        this.setSize(500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

JScrollPanel

package src.swing.Icon;

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

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

        //文本域
        JTextArea jTextArea = new JTextArea(10, 10);
        jTextArea.setText("JScrollTest");

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(jTextArea);//把文本域添加到面板上,不是scrollPane.add(jTextArea)
        container.add(scrollPane);

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

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

3.5、按钮

package src.swing.Icon;

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

public class JButtonDemo01 extends JFrame {
    public JButtonDemo01(){
        Container container = getContentPane();
        //将一个图片变为图标
        URL resource = JButtonDemo01.class.getResource("Mysql外键约束.png");
        Icon icon = new ImageIcon(resource);

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

        container.add(button);
        this.setVisible(true);
        this.setBounds(100,100,200,200);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

单选按钮

package src.swing.Icon;

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

public class JButtonDemo02 extends JFrame {
    public JButtonDemo02(){
        Container container = getContentPane();
        //将一个图片变为图标
        URL resource = JButtonDemo02.class.getResource("Mysql外键约束.png");

        //单选框
        JRadioButton jRadioButton1 = new JRadioButton("jRadioButton1");
        JRadioButton jRadioButton2 = new JRadioButton("jRadioButton2");
        JRadioButton jRadioButton3 = new JRadioButton("jRadioButton3");

        //由于单选框只能选择一个,需要分组,一个组中只能选择一个
        ButtonGroup group = new ButtonGroup();
        group.add(jRadioButton1);
        group.add(jRadioButton2);
        group.add(jRadioButton3);

        container.add(jRadioButton1,BorderLayout.CENTER);
        container.add(jRadioButton2,BorderLayout.NORTH);
        container.add(jRadioButton3,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setBounds(100,100,200,200);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

复选按钮

package src.swing.Icon;

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

public class JButtonDemo03 extends JFrame {
    public JButtonDemo03(){
        Container container = getContentPane();
        
        //多选框
        JCheckBox jCheckBox1 = new JCheckBox("checkbox01");
        JCheckBox jCheckBox2 = new JCheckBox("checkbox02");

        container.add(jCheckBox1,BorderLayout.NORTH);
        container.add(jCheckBox2,BorderLayout.SOUTH);

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

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

3.6、列表

下拉框

package src.swing.Icon;

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

public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01(){
        Container container = getContentPane();

        JComboBox<Object> status = new JComboBox<>();

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

        container.add(status);

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

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

列表框

package src.swing.Icon;

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

public class TestComboboxDemo02 extends JFrame {
    public TestComboboxDemo02(){
        Container container = getContentPane();
        //生成列表内容
        //String[] contents = {"1","2","3"};

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

        contents.add("zhangsan");
        contents.add("lisi");
        contents.add("wangwu");

        container.add(jList);

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

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

应用场景

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

3.7、文本框

  • 文本框
package src.swing.Icon;

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

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

        JTextField textField1 = new JTextField("Hello");
        JTextField textField2 = new JTextField("World",20);

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

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

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

  • 密码框
package src.swing.Icon;

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

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

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

        container.add(passwordField);

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

    public static void main(String[] args) {
        new TestTextDemo02();
    }
}
  • 文本域
package src.swing.Icon;

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

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

        //文本域
        JTextArea jTextArea = new JTextArea(10, 10);
        jTextArea.setText("JScrollTest");

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(jTextArea);//把文本域添加到面板上,不是scrollPane.add(jTextArea)
        container.add(scrollPane);

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

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

贪食蛇

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

package src.swing.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.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //游戏应该都在一个panel上面
        frame.add(new GamePanel());
        frame.setVisible(true);
    }
}
package src.swing.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;

/*
* 1.定义数据
* 2.画上去
* 3.监听事件
*     键盘监听
*     事件监听
* */

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

    //定义蛇的数据结构
    //蛇的长度
    int length;
    int[] snakeX = new int[600];//蛇的 X 坐标 25*25
    int[] snakeY = new int[500];//蛇的 Y 坐标 25*25
    String fx;
    int score;

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

    //游戏当前状态:开始,停止
    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] = 100;snakeY[0] = 100;//脑袋的坐标
        snakeX[1] = 75;snakeY[1] = 100;//第一个身体的坐标
        snakeX[2] = 50;snakeY[2] = 100;//第二个身体的坐标
        fx = "R";//初始方向向右
        timer.start();//定时器开启!

        score = 0;
        //把食物随机分布在界面上!
        foodx = 25 + 25*random.nextInt(34);
        foody = 75 + 25*random.nextInt(24);

    }

    //绘制面板,我们游戏中所有的东西,都是用这个画笔来画
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        this.setBackground(Color.WHITE);
        Data.header.paintIcon(this,g,25,11);//头部广告栏画上去
        g.fillRect(25,75,850,600);//默认的游戏界面

        //画积分
        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));//设置字体
            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";
            //repaint();
        }else if(KeyCode == KeyEvent.VK_DOWN){
            fx = "D";
            //repaint();
        }else if(KeyCode == KeyEvent.VK_LEFT){
            fx = "L";
           // repaint();
        }else if(KeyCode == KeyEvent.VK_RIGHT){
            fx = "R";
            //repaint();
        }

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

                //吃食物
                if(snakeX[0] == foodx && snakeY[0] == foody){
                    length++;//身体长度 +1

                    //分数加10
                    score = score + 10;

                    //再次随机食物的坐标
                    foodx = 25 + 25*random.nextInt(34);
                    foody = 75 + 25*random.nextInt(24);
                }

                //移动
                for (int i = length - 1; i > 0; i--) { //后一格移动到前一格的位置
                    snakeX[i] = snakeX[i-1];
                    snakeY[i] = snakeY[i-1];
                }

                //走向
                if(fx.equals("R")){
                    snakeX[0] = snakeX[0] + 25;
                    if(snakeX[0] > 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 < length ; i++) {
                    if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
                        isFail = true;
                    }
                }
                repaint();//重画页面
            }
            timer.start();//定时器开启!
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}
package src.swing.snake;

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

//数据中心
public class Data {
    //相对路径
    //绝对路径 / 相当于当前的项目
    public static URL headerURl = Data.class.getResource("staticspicture/head.png");
    public static ImageIcon header = new ImageIcon(headerURl);

    public static URL upURl = Data.class.getResource("staticspicture/up.png");
    public static URL downURl = Data.class.getResource("staticspicture/down.png");
    public static URL leftURl = Data.class.getResource("staticspicture/left.png");
    public static URL rightURl = Data.class.getResource("staticspicture/right.png");

    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("staticspicture/body.png");
    public static ImageIcon body = new ImageIcon(bodyURl);

    public static URL foodURl = Data.class.getResource("staticspicture/food.png");
    public static ImageIcon food = new ImageIcon(foodURl);
}

posted @   冷月_1991  阅读(52)  评论(1编辑  收藏  举报
相关博文:
·  JavaWeb
·  JavaScript
·  GUI编程
·  Java GUI
·  javaGUI
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示