IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> PHP知识库 -> java GUI编程 -> 正文阅读

[PHP知识库]java GUI编程

GUI编程

GUI(Graphical User Interface)

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

1.简介

Java的GUI的核心技术:Swing AWT(但很少使用到)

  1. 因为界面不美观

  2. 需要jre环境!

为什么我们需要学习?

  1. 可以写出自己心中想要的一些小工具
  2. 工作时候,也可能维护到需要swing界面(概率极小,只有比较老的公司可能会用到)
  3. 了解MVC架构,了解监听

2.AWT(Abstract Window Toolkit,抽象窗口工具包)

2.1 AWT介绍

  1. 包括很多类和接口
  2. 元素:窗口 按钮 文本框
  3. java.awt包
  4. [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Cvs6tefo-1630763980399)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821105429213.png)]

2.2 组件与容器

1. Frame

import java.awt.*;

public class TestFrame {
    public static void main(String[] args) {
        //Frame JDK看原码!
        Frame frame = new Frame("我的第一个Java图形界面");
        //需要设置可见性,否则默认不可见 w h
        frame.setVisible(true);
        //设置窗口大小
        frame.setSize(200,200);
        //设置背景颜色
        frame.setBackground(new Color(200,100,90));
        //设置初始位置
        frame.setLocation(200,200);
        //设置大小固定
        frame.setResizable(false);
        //frame.setBounds(200,200,100,200);
        }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tvS6QV3U-1630763980401)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821112637065.png)]

但窗口无法关闭

尝试回顾封装

import java.awt.*;

public class TestFrame2 {
    public static void main(String[] args) {
        MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.BLUE);
        MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.MAGENTA);
        MyFrame myFrame3 = new MyFrame(500, 100, 200, 200, Color.YELLOW);
        MyFrame myFrame4 = new MyFrame(700, 100, 200, 200, Color.PINK);
    }
}
class MyFrame extends Frame{
    static int id = 0;
   public MyFrame(int x,int y,int width,int height,Color color){
       super("MyFrame id"+(id++));
       setVisible(true);
       setBounds(x,y,width,height);
       setBackground(color);
   }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OvqWXX1v-1630763980402)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821154301538.png)]

2. Panel

解决了关闭事件

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

//Panel可以看成时一个空间,但不能独立存在
public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Panel panel = new Panel();
        //设置布局
        frame.setLayout(null);
        frame.setBounds(200,200,400,400);
        frame.setBackground(new Color(146, 47, 200));
        //Panel设置坐标,相对于frame
        panel.setBounds(50,50,200,200);
        panel.setBackground(new Color(156, 190, 64));
        //frame.add(panel)
        // Panel继承Container,Container继承Component,add方法可添加组件
        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);
            }
        });
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hz9K1JTj-1630763980405)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821164836290.png)]

2.3 布局管理器

  • 流式布局FlowLayout
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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");
        //设置为流式布局,默认为center
        //frame.setLayout(new FlowLayout());
        //frame.setLayout(new FlowLayout(FlowLayout.LEADING));
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        //frame.setLayout(new FlowLayout(FlowLayout.TRAILING));
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
        frame.setBounds(200,200,300,300);
        //添加按钮
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.exit(0);
            }
        });

    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vwMqkoRu-1630763980406)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821200839813.png)]

  • 东西南北中BorderLayout
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("东西南北中布局测试窗口");
        //组件-按钮
        Button button1 = new Button("East");
        Button button2 = new Button("West");
        Button button3 = new Button("South");
        Button button4 = new Button("North");
        Button button5 = new Button("Centre");
        frame.setLayout(new BorderLayout());
        frame.setBounds(200,200,300,300);
        //添加按钮
        frame.add(button1,BorderLayout.EAST);
        frame.add(button2,BorderLayout.WEST);
        frame.add(button3,BorderLayout.SOUTH);
        frame.add(button4,BorderLayout.NORTH);
        frame.add(button5,BorderLayout.CENTER);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.exit(0);
            }
        });

    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6VAlsObv-1630763980408)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821202909261.png)]

  • 表格式布局GridLayout
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("表格式布局测试窗口");
        //组件-按钮
        Button button1 = new Button("East");
        Button button2 = new Button("West");
        Button button3 = new Button("South");
        Button button4 = new Button("North");
        Button button5 = new Button("Centre");
        frame.setLayout(new GridLayout());
        frame.setBounds(200,200,300,300);
        //添加按钮
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.exit(0);
            }
        });
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qQbGyJD5-1630763980409)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821204334843.png)]

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M5WNVItW-1630763980410)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821213938863.png)]

  • GridBagLayout布局
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestGridBagLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("GridBag布局测试窗口");
        //组件-按钮
        Button button1 = new Button("East");
        Button button2 = new Button("West");
        Button button3 = new Button("South");
        Button button4 = new Button("North");
        Button button5 = new Button("Centre");
        frame.setLayout(new GridBagLayout());
        frame.setBounds(200,200,300,300);
        //添加按钮
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.exit(0);
            }
        });
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SRCKqJs6-1630763980412)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210821204551421.png)]

  • 练习

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b3bpZ1MA-1630763980413)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210823153746921.png)]

  • 先分析实现过程
  • 再代码实现
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ExFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setLayout(new GridLayout(2,1));
        frame.setVisible(true);
        frame.setBounds(300,300,400,300);
        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("WEST-1"),BorderLayout.WEST);
        p1.add(new Button("EAST-1"),BorderLayout.EAST);
        p2.add(new Button("up-1"));
        p2.add(new Button("down-1"));
        p1.add(p2,BorderLayout.CENTER);
        frame.add(p1);
        p3.add(new Button("WEST-1"),BorderLayout.WEST);
        p3.add(new Button("EAST-1"),BorderLayout.EAST);
        for (int i = 0; i < 4; i++) {
            p4.add(new Button("B-"+(i)));
        }
        p3.add(p4,BorderLayout.CENTER);
        frame.add(p3);

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PRk7Xqy5-1630763980414)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210823203316458.png)]

总结

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

2.4 事件监听

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 TestListener01 {
    //点击按钮时,触发一些事件
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(300,300,400,500);
        Button button = new Button("button");
        button.setBounds(500,500,100,100);
        //因为addActionListener需要一个ActionListener,所以我们构造一个MyActionListener
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);
        windowclose(frame);
        frame.add(button,BorderLayout.CENTER);
        frame.setVisible(true);

    }
    //关闭窗口的事件
    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("这是一个按钮!");
    }
}

多个按钮共享一个监听事件

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("这是一个开始结束窗口");
        frame.setVisible(true);
        frame.setBounds(300,300,400,300);
        windowClose(frame);
        Button b1 = new Button("start");
        Button b2 = new Button("stop");
        MyMonitor myMonitor = new MyMonitor();
        b1.addActionListener(myMonitor);
        //可以显式地定义出发会返回的命令,如果不显式定义,则会走默认的值
        //可以多个按钮致谢一个监听类
        b2.setActionCommand("button-stop");
        b2.addActionListener(myMonitor);

        frame.add(b1,BorderLayout.NORTH);
        frame.add(b2,BorderLayout.SOUTH);
    }
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

//事件监听
class MyMonitor implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand() == "start"){
            System.out.println("开始啦");
        }else if(e.getActionCommand()=="stop"){
            System.out.println("结束啦");
        }

    }
}

2.5 文本框TextField监听

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 TestTextF1 {
    public static void main(String[] args) {
        MyFrame myFrame = new MyFrame();
    }
}
class MyFrame extends Frame{
    public MyFrame(){
        super("文本框");
        setBounds(300,300,300,300);
        setVisible(true);
        TextField textField = new TextField();
        MyActionListener2 myActionListener2 = new MyActionListener2();
        textField.addActionListener(myActionListener2);
        textField.setEchoChar('*');
        add(textField);
        windowClose(this);
    }
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
class MyActionListener2 implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field = (TextField) e.getSource();
        System.out.println(field.getText());
        field.setText("");
    }
}

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

OOP原则: 组合大于继承!

//继承
class A extends B{

}
//组合
class A{
   ppublic B b;
}
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 TestCalculator {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
    }
}
//计算器类
class Calculator extends Frame{
    public Calculator(){
        //三个文本框
        TextField num1 = new TextField(10);
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(20);
        //一个标签
        Label label = new Label("+");
        //一个按钮
        Button button = new Button("=");
        CalculatorListener calculatorListener = new CalculatorListener(num1,num2,num3);
        button.addActionListener(calculatorListener);
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        setLayout(new FlowLayout());
        pack();
        setVisible(true);
        //setBounds(300,300,1000,200);
        windowClose(this);
    }
    public void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//监听器类
class CalculatorListener implements ActionListener{
    private TextField num1,num2,num3;

    public CalculatorListener(TextField num1,TextField num2,TextField num3){
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取前两个数,并相加,清除前两个框
        int n1 = Integer.parseInt(num1.getText());
        int n2 = Integer.parseInt(num2.getText());
        num3.setText(""+(n1+n2));
        num1.setText("");
        num2.setText("");
    }
}

完全改造为面向对象(改造为组合)

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 TestCalculator {
    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);
        //一个标签
        Label label = new Label("+");
        //一个按钮
        Button button = new Button("=");
        CalculatorListener calculatorListener = new CalculatorListener(this);
        button.addActionListener(calculatorListener);
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        setLayout(new FlowLayout());
        pack();
        setVisible(true);
        //setBounds(300,300,1000,200);
        windowClose(this);
    }
    public void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//监听器类
class CalculatorListener implements ActionListener{
    //获取计算器这个类,在一个类中组合另一个类,仍然需要重复,而不能直接调用该类的属性和方法
    Calculator calculator = null;

    public CalculatorListener(Calculator calculator){
        this.calculator = calculator;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取前两个数,并相加,清除前两个框
        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("");
    }
}

内部类

  • 更好的包装
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 TestCalculator {
    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);
        //一个标签
        Label label = new Label("+");
        //一个按钮
        Button button = new Button("=");
        button.addActionListener(new CalculatorListener());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        setLayout(new FlowLayout());
        pack();
        setVisible(true);
        windowClose(this);
    }
    //监听器类
    //内部类最大的好处,就是内部类可以畅通无阻地访问外部类的方法和属性
    class CalculatorListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            //获取前两个数,并相加,清除前两个框
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());
            num3.setText(""+(n1+n2));
            num1.setText("");
            num2.setText("");
        }
    }
    public void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

2.7 画笔

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

public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}
class MyPaint extends Frame{

    public void loadFrame(){
        setVisible(true);//加载窗口
        setBounds(100,100,600,600);
        setResizable(false);
        windowClose(this);
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.blue);
        g.drawRect(100,100,100,200);
        g.setColor(Color.green);
        g.fillOval(300,200,200,200);
    }

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


总结:每次画完,画笔需返回初始设置的颜色

2.8 鼠标监听事件

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

public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrameMouse("画板");
    }
}
//建一个属于自己的类,进行画画
class MyFrameMouse extends Frame{
    //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这些画出的点
    ArrayList points;
    public MyFrameMouse(String title){
        super(title);
        setVisible(true);
        setBounds(100,200,500,300);
        //此处需要一个集合来存鼠标画的点
        points = new ArrayList<>();
        //鼠标监听器,针对这个窗口
        this.addMouseListener(new MyMouseListener());
        //窗口监听器
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    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 implements MouseListener{  }
    //添加一个点到界面上
    private class MyMouseListener extends MouseAdapter{
        //鼠标  按下,弹起,按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrameMouse myFrameMouse = (MyFrameMouse) e.getSource();//返回当前对象
            //当我们点击的时候,界面上会出现一个点,,并画出来,这个点就是鼠标的点。
            myFrameMouse.addPaint(new Point(e.getX(),e.getY()));
            myFrameMouse.repaint();  //每次点击重新画一次

        }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0ca7laZd-1630763980416)(C:\Users\Administrator\Downloads\未命名文件.jpg)]

2.9 窗口监听

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

public class TestWindowListener {
    public static void main(String[] args) {
        new MyWindowListener("窗口监听");
    }
}
class MyWindowListener extends Frame {
    public MyWindowListener(String title) {
        super(title);
        setVisible(true);
        setBackground(Color.pink);
        setBounds(100, 100, 400, 500);
        //this.addWindowListener(new MyWindowListener1());
        //this.addWindowListener(new MyWindowListener2());
        //匿名内部类
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("windowActivated");
            }
        });

    }

    private class MyWindowListener1 implements 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) {
            System.out.println("windowActivated");
        }

        @Override
        public void windowDeactivated(WindowEvent e) {

        }

    }//接口需要实现所有方法,太多,可以使用继承适配器的方式
    private class MyWindowListener2 extends WindowAdapter {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }
}

2.10 键盘监听

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

public class TestKeyListener {
    public static void main(String[] args) {
        new MyTestKeyListener("键盘监听");
    }
}
//定义自己的类
class MyTestKeyListener extends Frame{
    public MyTestKeyListener(String title){
        super(title);
        setVisible(true);
        setBackground(Color.pink);
        setBounds(100,200,500,300);
        this.addKeyListener(new MyKeyListener());
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    private class MyKeyListener extends KeyAdapter{

        @Override
        public void keyPressed(KeyEvent e) {
            super.keyPressed(e);
            System.out.println(e.getKeyCode());

            System.out.println("已按下");
            if(e.getKeyCode()== KeyEvent.VK_DOWN){
                System.out.println("你这是下键!!");
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            super.keyReleased(e);
            System.out.println("已释放");
        }

        @Override
        public void keyTyped(KeyEvent e) {
            super.keyTyped(e);
            System.out.println("keytyped");
            System.out.println(e.getSource());
        }
    }

}

3.Swing

3.1 窗口,面板

  • JFrame继承了Frame
  • 需要在容器上加组件
  • 有自动关闭窗口的函数,不用监听器
  • 不用布局管理器
import javax.swing.*;
import java.awt.*;

public class JFrameDemo01 {
    //init 初始化
    public void init(){
        //顶级窗口
        JFrame jf = new JFrame("THIS IS A JFRAME");
        jf.setVisible(true);
        jf.setBounds(100,100,200,100);

        JLabel label = new JLabel("欢迎来到中国!");
        //label.setBounds(50,50,100,50);
        jf.add(label);
        label.setHorizontalAlignment(SwingConstants.CENTER);//设置文本位置

        Container pane = jf.getContentPane();
        pane.setBackground(Color.green);

        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//升级之后的JFrame设置了自动关闭窗口

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


3.2 弹窗

  • 设置JLabel位置之后,JLabel才可见
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//主窗口
public class DialogDemo01 extends JFrame{
    public DialogDemo01(){
        //需要一个按钮,弹窗位置如何放置
        this.setVisible(true);
        this.setBounds(100,100,400,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //JFrame上需要一个容器放东西
        Container container = this.getContentPane();
        container.setBackground(Color.green);
        //绝对布局
        container.setLayout(null);
        //按钮
        JButton button = new JButton("弹出一个弹窗");
        button.setBounds(50,50,200,100);
        container.add(button);
        //鼠标监听事件
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyDialog();
            }
        });

    }

    public static void main(String[] args) {
        new DialogDemo01();
    }
}
//弹窗的窗口
class MyDialog extends JDialog{
    public MyDialog(){
        this.setVisible(true);
        this.setBounds(100,100,400,300);
        Container container = this.getContentPane();
        container.setBackground(Color.pink);
        container.setLayout(null);
        JLabel label = new JLabel("WELCOME TO A NEW JDIALOG");
        label.setVisible(true);
        label.setBounds(100,100,300,100);//设置位置之后,JLabel才可见
       add(label);
    }

}

3.3 标签

  • 图片标签,JLabel上放图标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 imageIcon = new IconDemo(100, 100);

        JLabel label = new JLabel("XXX",imageIcon,SwingConstants.CENTER);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);

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

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

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

    @Override
    public int getIconWidth() {
        return this.width;//返回图标的宽
    }

    @Override
    public int getIconHeight() {
        return this.height;//返回图标的高
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gZc44BDn-1630763980416)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210904194017011.png)]

  • JLabel上可以添加ImageIcon,图片 ICON
import javax.swing.*;
import java.awt.*;
import java.net.URL;

//图标是一个接口,需要实现类,Frame是一个类,需要继承
public class IconDemo extends JFrame{
    public IconDemo(){
        JLabel label = new JLabel("ImageIcon");
        URL url = IconDemo.class.getResource("gq.jpg");

        //label.setBounds(10,10,100,100);
        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        //容器
        Container container = getContentPane();
        container.add(label);

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iw0OHMWq-1630763980418)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210904194120554.png)]

3.4 面板

  • JPanel

    import javax.swing.*;
    import java.awt.*;
    
    public class JPanelDemo extends JFrame{
        public JPanelDemo(){
            //所有东西需要放入容器
            Container container = getContentPane();
            container.setLayout(new GridLayout(2,2,20,20));//后两个参数位间距
    
            JPanel jPanel1 = new JPanel(new GridLayout(2,2));
            jPanel1.add(new JButton("面板一"));
            jPanel1.add(new JButton("面板2"));
            jPanel1.add(new JButton("面板3"));
            JPanel jPanel2 = new JPanel();
            jPanel2.setLayout(new GridLayout(1,3));
            jPanel2.add(new JButton("HHHHA"));
            jPanel2.add(new JButton("HHHHA"));
            jPanel2.add(new JButton("HHHHA22"));
            JPanel jPanel3 = new JPanel(new GridLayout());
            jPanel3.add(new JButton("面板一"));
            jPanel3.add(new JButton("面板2"));
            jPanel3.add(new JButton("面板3"));
            jPanel3.add(new JButton("面板3"));
            JPanel jPanel4 = new JPanel(new GridLayout());
            jPanel4.add(new JButton("4"));
            jPanel4.add(new JButton("4"));
            jPanel4.add(new JButton("4"));
    
            container.add(jPanel1);
            container.add(jPanel2);
            container.add(jPanel3);
            container.add(jPanel4);
    
            setVisible(true);
            setBounds(100,100,400,300);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new JPanelDemo();
        }
    }
    
  • 滚动框JScrollPane

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

public class JScrollDemo extends JFrame{
    public JScrollDemo(){
        Container container = getContentPane();
        
        JTextArea jTextArea = new JTextArea();
        jTextArea.setText("多想一醒来 晨风就能抚平忧伤\n" +
                "多想一转身 目光就融化掉冰霜\n" +
                "多想一抬头 看见你微笑的脸庞\n" +
                "多想你能够 把喜怒哀乐 对我讲");
        JScrollPane jScrollPane = new JScrollPane(jTextArea);

        container.add(jScrollPane);

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ibW2oaF3-1630763980418)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210904203921147.png)]

3.5 按钮

  • JButton
    1. 将图片变为图标
    2. 按钮上添加图标
    3. 按钮上悬浮提示信息
package com.raylene.GUI.swing;

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

public class JButtonDemo01 extends JFrame{
    public JButtonDemo01(){
        Container container = getContentPane();
        container.setLayout(new GridLayout());
        //将一个图片变为一个图标
        URL url = JButtonDemo01.class.getResource("gq.jpg");
        Icon imageIcon = new ImageIcon(url);

        JButton jButton = new JButton();
        jButton.setIcon(imageIcon);
        jButton.setToolTipText("图片按钮");//图片悬浮提示消息

        container.add(jButton);

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-v16knsYo-1630763980419)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210904210037409.png)]

  • 单选按钮

    1. 由于单选框同时只有一个可以被选中,所以需要建一个组
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    
    public class JButtonDemo02 extends JFrame{
        public JButtonDemo02(){
            Container container = getContentPane();
            //将一个图片变为一个图标
            URL url = JButtonDemo01.class.getResource("gq.jpg");
            Icon imageIcon = new ImageIcon(url);
    
            JRadioButton radioButton01 = new JRadioButton("jRadioButton01");
            JRadioButton radioButton02 = new JRadioButton("jRadioButton02");
            JRadioButton radioButton03 = new JRadioButton("jRadioButton03");
            //由于单选框同时只有一个可以被选中,所以需要建一个组
            ButtonGroup group = new ButtonGroup();
            group.add(radioButton01);
            group.add(radioButton02);
            group.add(radioButton03);
            
            
            container.add(radioButton01,BorderLayout.NORTH);
            container.add(radioButton02,BorderLayout.CENTER);
            container.add(radioButton03,BorderLayout.SOUTH);
            
            setVisible(true);
            setBounds(100,100,400,300);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new JButtonDemo02();
        }
    }
    
  • 复选按钮

    1. 多选框不需要建组
import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class JButtonDemo03 extends JFrame {
    public JButtonDemo03(){
        Container container = getContentPane();
        //将一个图片变为一个图标
        URL url = JButtonDemo01.class.getResource("gq.jpg");
        Icon imageIcon = new ImageIcon(url);

        JCheckBox checkBox01 = new JCheckBox("checkBox01");
        JCheckBox checkBox02 = new JCheckBox("checkBox02");
        JCheckBox checkBox03 = new JCheckBox("checkBox03");
        
        //多选框不需要分组
        container.add(checkBox01,BorderLayout.NORTH);
        container.add(checkBox02,BorderLayout.CENTER);
        container.add(checkBox03,BorderLayout.SOUTH);

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

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

3.6 列表

  • 下拉框JComboBox

  • 1.将下拉框放入面板更美观

    import javax.swing.*;
    import java.awt.*;
    
    public class ComboBoxDemo01 extends JFrame{
        public ComboBoxDemo01(){
            Container container = getContentPane();
    
            JComboBox box = new JComboBox();
            box.setBounds(100,100,100,20);
            box.addItem("空空如也");
            box.addItem("火热上映中");
            box.addItem("已下架");
            box.addItem("即将上映");
    
            JPanel panel = new JPanel();
            panel.setBounds(100,100,200,10);
            panel.add(box);
    
            container.add(panel,BorderLayout.WEST);
    
            setVisible(true);
            setBounds(100,100,300,200);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new ComboBoxDemo01();
        }
    }
    
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lNVwwOkC-1630763980420)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210904213436970.png)]

  • 列表框

    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    
    public class ComboBoxDemo02 extends JFrame{
        public ComboBoxDemo02(){
            Container container = getContentPane();
            {/*
            //生成列表的内容
            String[] contents = {"1","2","3","4"};//静态初始化
            //列表中需要放入内容
            JList list = new JList(contents);
    
            container.add(list);
    
             */}
            {
                Vector contents = new Vector();
                JList list = new JList(contents);
                container.add(list);
                contents.add("a");
                contents.add("w");
                contents.add("e");
                contents.add("r");
                contents.add("t");
            }
    
            setVisible(true);
            setBounds(100,100,400,300);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new ComboBoxDemo02();
        }
    }
    
    
  • 应用场景

    1. 下拉框:当内容超过2个时,选择一些选项
    2. 列表,展示信息,一般是动态扩容的

3.7 文本框

  • 文本框

    import javax.swing.*;
    import java.awt.*;
    
    public class TextDemo01 extends JFrame{
        public TextDemo01() {
            Container container = getContentPane();
    
            JTextField field1 = new JTextField("hhhhhh1");
            JTextField field2 = new JTextField("hhhhhh2");
    
            container.add(field1,BorderLayout.NORTH);
            container.add(field2,BorderLayout.SOUTH);
    
            setVisible(true);
            setBounds(100,100,400,300);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new TextDemo01();
        }
    }
    
  • 文本域 JTextArea

  • 密码框

    import javax.swing.*;
    import java.awt.*;
    
    public class TextDemo02 extends JFrame{
        public TextDemo02() {
            Container container = getContentPane();
    
            JPasswordField field1 = new JPasswordField("HBXVH1");//****
            JPasswordField field2 = new JPasswordField("HBXVH2");//****
            JPasswordField field3 = new JPasswordField("HBXVH3");//****
            field1.setEchoChar('#');
    
            container.add(field1,BorderLayout.NORTH);
            container.add(field2,BorderLayout.SOUTH);
            container.add(field3,BorderLayout.CENTER);
    
            setVisible(true);
            setBounds(100,100,400,300);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new TextDemo02();
        }
    }
    
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ogE6EotL-1630763980422)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210904215834080.png)]

  PHP知识库 最新文章
Laravel 下实现 Google 2fa 验证
UUCTF WP
DASCTF10月 web
XAMPP任意命令执行提升权限漏洞(CVE-2020-
[GYCTF2020]Easyphp
iwebsec靶场 代码执行关卡通关笔记
多个线程同步执行,多个线程依次执行,多个
php 没事记录下常用方法 (TP5.1)
php之jwt
2021-09-18
上一篇文章      下一篇文章      查看所有文章
加:2021-09-06 10:56:57  更:2021-09-06 10:58:42 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/15 10:14:50-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码