精华内容
下载资源
问答
  • java GUI编程

    2020-12-20 19:40:59
    java GUI编程 awt和swing awt:抽象窗口工具集 所属包:java.awt swing:awt的拓展,不是替换 swing继承了awt的许多类,因此使用swing类库的时候间接使用了awt类库 所属包:javax.swing component类中的常用...

    java GUI编程

    awt和swing
    • awt:抽象窗口工具集
      • 所属包:java.awt
    • swing:awt的拓展,不是替换
      • swing继承了awt的许多类,因此使用swing类库的时候间接使用了awt类库
      • 所属包:javax.swing
    • component类中的常用方法:
      • String getName() 获得组件的名称

      • Container getParent() 获得直接容纳该组件的容器

      • boolean isFocusable() 判断组件是否可以获得焦点

      • boolean isFocusOwner() 判断组件是否获得了焦点

      • void setEnabled(boolean b) 设置组件是否被屏蔽(例如按钮如果是false就是变灰不可点击)

      • boolean isEnabled() 判断组件是否被屏蔽

      • void setSize(int width,int height) 设置组件的尺寸

      • void setVisible(boolean b) 设置组件是否可见

      • boolean isVisible() 判断组件是否可见

      • void setLocation(int x,int y) 指定组件显示的位置

        • 一个小例子
    public class TestFrame {
        public static void main(String[] args) {
            //通过跟进看源码和构造器
            Frame frame=new Frame("第一个窗口");
            //设置可见性
            frame.setVisible(true);
            //窗口大小
            frame.setSize(400,400);
            //背景颜色
            frame.setBackground(new Color(56, 146, 255));
            //窗口位置
            frame.setLocation(200,200);
            //设置大小固定
            frame.setResizable();
        }
    }
    

    在这里插入图片描述

    编写GUI的步骤
    • 构造界面:构造组件对象
      • 构造容器对象+构造组件对象+add方法
    • 美化界面:对容器组件合理布局
    • 响应界面:给界面加入事件处理机制
    • Component类中的一些常用的方法
      • Container 类中的常用方法:
        • Component add(Component comp) 将组件加到容器中
        • void remove(Component comp) 将组件从容器中移除
        • void setLayout(LayoutManager mgr) 设置容器的布局
      • Frame 类的常用方法:
        • void setTitle(String s) 设置标题
        • String getTitle() 获取标题
      • Label 类、TextField 类的常用方法:
        void setText(String s) 设置文本信息
        String getText() 获取文本信息
      • Button 类的常用方法:
        • void setLabel(String s) 设置按钮的标签信息,不是组件名称,只是标签上面的内容而不是按钮的名字
        • String getLabel() 获取按钮的标签信息
    • FlowLayout 布局类: 组件从左到右,逐行依次摆放
    • GridLayout 布局类: 将容器分割成同等大小的网格
    • Font类:Font f1=new Font(" 宋体" , Font.BOLD , 23);
    package GUI;
    import java.awt.*;
    import javax.swing.*;
    
    public class GuiPra extends JFrame{
        GuiPra(){
            super("练习");
        }
        public void f(){
            setSize(400,400);
            setBackground(Color.ORANGE);
            setLocation(300,300);
            setLayout(new FlowLayout());
            add(new Label("用户名:"));
            add(new JTextField(5));
            add(new Label("密码:"));
            add(new TextField(5));
            add(new JButton("登录"));
            add(new JButton("退出"));
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new GuiPra().f();
        }
    }
    
    

    在这里插入图片描述

    注意Label和JLabel区别:JLabel 的setBackground 是继承自JComponent , 而JComponent 的setOpaque(boolean) 默认情况下是false ,背景透明而无法显示底层像素因此如果要用到JLabel的背景设置则需要将方法改成true

    创建图形界面的5个步骤
    • 创建JFrame窗体
    • 对窗体设置大小位置背景布局等等
    • 定义一系列需要的组件
    • 将组件通过add方法添加到窗体里
    • 让窗体显示:setVisible
    委托事件处理模型
    • 三要素:事件源、事件、事件处理者(监听器)
    • 三步骤:
      • 确定事件源和事件
      • 定义处理者即实现相关事件的接口
      • 关联事件源和事件处理者
    package Practice2;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class Guipra2 extends JFrame implements ActionListener{
        private JButton bok,bexit;
        private JTextField username;
        private Label tla;
        private JPasswordField password;
        public Guipra2(){
            super("一个界面");
        }
        public void f(){
            setSize(400,400);
            setLocation(300,300);
            setBackground(Color.GRAY);
            setLayout(new FlowLayout());
            username=new JTextField(5);
            password=new JPasswordField(5);
            add(new Label("用户名:"));
            add(username);
            add(new Label("密码:"));
            add(password);
            bok=new JButton("确定");
            bexit=new JButton("退出");
            add(bok);
            add(bexit);
            add(new Label("  "));
            tla=new Label("  ");//提示信息的标签
            add(tla);
            setVisible(true);
            //GUI界面设计部分
            bexit.addActionListener(this);//建立关联
            bok.addActionListener(this);
        }
        public  void actionPerformed(ActionEvent e){
        	//发生按钮点击事件监听器必须实现与事件对应的接口AcctionListener,并且自动调用事件处理方法actionPerformed
            if (e.getSource()==bexit)
                System.exit(0);
            if (e.getActionCommand().equals("确定")){
                String KeyText=String.valueOf(password.getPassword());
                //将字符数组转换成字符串
                if(username.getText().equals("why")&&password.getPassword().equals("1234"))
                    tla.setText("欢迎你");
                else
                    tla.setText("用户名或者密码输入错误");
                setVisible(true);
            }
        }
    
        public static void main(String[] args) {
            Guipra2 g=new Guipra2();
            g.f();
        }
    }
    
    
    

    在这里插入图片描述

    • 注意点:在java类库中每个事件源能产生的事件是确定的,与之匹配的事件监听器接口也是确定的,与监听器建立关联的方法也是确定的。比如上面例子中的JButton的对象可以产生ActionEvent事件,那么相应建立关联的方法就是addActionListener(ActionListener e)
      • 并且监听器接口中有特定的方法,该方法其实就是完成时间处理的方法,例如上面例子中的 public void actionPerformed(ActionEvent e)
      • 实现窗体的关闭动作:
        • 实现WindowListener接口
        • 重写接口中的7个方法,其中只需要利用public void WindowClosing(WindowEvent e){System.exit(0);}
    由窗口关闭引出的适配器类
    • 由于监听器必须要实现监听器接口中的所有抽象方法比较麻烦且像窗口关闭只需要用到一个方法却要重写7个方法
    • 第二种窗口关闭的方法
    //定义一个内部类
    class A extents WindowAdapter{
    	public void WindowClosing(WindowEvent e){System.exit(0);}
    	//在构造函数中加入下面语句
    	this.addWindowListener(new A());
    }
    
    • 第三种关闭窗体的方法
      • 由于关闭窗口是Frame常用特性,因此JFrame提供了静态int型常量EXIT_ON_CLOSE
    JFrame f=new JFrame("why的界面");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    布局管理
    • 设定布局的方法:void setLayout(LayoutManager m)
    • FlowLayout:流式布局
      • 默认时从左至右、从上到下逐行摆放
      • LEFT(左对齐)
      • RIGHT(右对齐)
      • CENTER(居中对齐)
      • LEADING(首对齐):主要是针对英文字母
      • TRAILING(尾对齐)
    setLayout ( new FlowLayout( FlowLayout.RIGHT ) );
    
    • GridLayout:网格布局
    setLayout(new GridLayout(3,2,5,10));//将容器等分成3 行*2 列个网格 ,每个网格只能放一个组件,且自动填满;网格水平间隙为5 ,纵向间隙为10,只能以行为序从左至右填写网格
    
    • BorderLayout:边界布局(默认的布局管理器)
      • 将容器分成东西南北中5 个区域,每个区域只能放一个组件,且自动填满可将组件放到指定区域,也可缺省某些区域
    add(new JButton("EAST"),BorderLayout.EAST);
    
    展开全文
  • Java GUI 编程

    2021-01-21 21:58:42
    GUI编程 核心技术:Swing AWT 界面不美观 需要jre环境 2. AWT 2.1 Awt介绍 包含了很多类和接口! GUI : 图形用户界面编程 元素:窗口、按钮、文本框 java.awt包 2.2 组件和容器 1. Frame public class ...

    GUI编程

    核心技术:Swing AWT

    1. 界面不美观

    2. 需要jre环境

    2. AWT

    2.1 Awt介绍

    1. 包含了很多类和接口! GUI : 图形用户界面编程
    2. 元素:窗口、按钮、文本框
    3. java.awt包

    2.2 组件和容器

    1. Frame

    public class TestFrame {
        public static void main(String[] args) {
    
            //  frame
            Frame frame = new Frame("我的第一个窗口");
    
            // 需要设置可见性
            frame.setVisible(true);
    
            // 大小
            frame.setSize(400, 400);
    
            // 颜色
            frame.setBackground(new Color(196, 149, 67));
    
            // 弹出初始位置
            frame.setLocation(300, 399);
    
            // 设置大小固定
            frame.setResizable(false);
        }
    }
    

    问题:运行后 点关闭没有反应

    尝试回顾封装:

    public class TestFrame02 {
        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.pink);
            MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.yellow);
            MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.red);
        }
    
    }
    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

    解决了 关闭问题

    适配器模式

    import java.awt.*;
    import java.awt.event.WindowAdapter;
    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();
    
            // 设置布局
            frame.setLayout(null);
    
            // 坐标
            frame.setBounds(300, 300, 500, 500);
            frame.setBackground(new Color(11, 231, 33));
    
            //panel 设置坐标
            panel.setBounds(50,50,400,400);
            panel.setBackground(new Color(239, 109, 162));
    
            // frame.add()
            frame.add(panel);
    
            frame.setVisible(true);
    
            //监听事件, 监听窗口关闭事件 system.exit(0)
            // 适配器模式
            frame.addWindowListener(new WindowAdapter() {
                // 窗口点击关闭的时候所需要的做的事情
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    

    3. 布局管理器

    • 流式布局
    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.CENTER));
            frame.setSize(200,200);
    
            // 把按钮添加上去
            frame.add(button1);
            frame.add(button2);
            frame.add(button3);
    
            frame.setVisible(true);
    
            frame.addWindowListener(new WindowAdapter() {
                // 窗口点击关闭的时候所需要的做的事情
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    
    • 东西南北中
    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.setVisible(true);
            frame.setSize(500,500);
    
        }
    }
    
    • 表格布局(Grid)
    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);
    
        }
    }
    
    public class Testbutton {
        public static void main(String[] args) {
            Frame frame = new Frame("欢迎来到button的世界");
    
            frame.setSize(400,300);
            frame.setLocation(300,400);
            frame.setBackground(Color.pink);
            frame.setVisible(true);
    
            frame.setLayout(new GridLayout(2,1));
    
            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("Ease-2"), BorderLayout.EAST);
            p3.add(new Button("West-2"), BorderLayout.WEST);
            p4.add(new Button("p4-btn-1"));
            p4.add(new Button("p4-btn-2"));
            p4.add(new Button("p4-btn-3"));
            p4.add(new Button("p4-btn-4"));
            p3.add(p4, BorderLayout.CENTER);
    
            frame.add(p1);
            frame.add(p3);
    
    
    
    
        }
    }
    

    总结:

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

    4. 事件监听

    鼠标,键盘、

    public class TestActionEvent {
        public static void main(String[] args) {
            // 按下按钮,出发一些事件
            Frame frame = new Frame();
            Button button = new Button();
    
            MyAcionListener myAcionListener = new MyAcionListener();
            button.addActionListener(myAcionListener);
    
            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 MyAcionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("aaa");
        }
    }
    

    两个按钮是否能公用一个事件呢?

    public class TestActionTwo {
        public static void main(String[] args) {
            // 两个按钮,实现同一个监听
            // 开始 停止
            Frame frame = new Frame("Srart     End");
            Button button1 = new Button("Srart");
            Button button2 = new Button("End");
    
            // 可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值
            // 可以多个按钮,只写一个监听类
            button2.setActionCommand("爱你一万年   2222 ");
    
            MyMonitor myMonitor = new MyMonitor();
    
            button1.addActionListener(myMonitor);
            button2.addActionListener(myMonitor);
    
            frame.add(button1, BorderLayout.NORTH);
            frame.add(button2, BorderLayout.SOUTH);
            frame.setVisible(true);
            frame.pack();
    
        }
    }
    class MyMonitor implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 获得按钮信息
            System.out.println("按钮被点击:" + e.getActionCommand());
    
    
        }
    }
    

    5.输入框TextField

    public class TestText01 {
        public static void main(String[] args) {
            // 启动
            new MyFrame();
    
        }
    }
    class MyFrame extends Frame {
        public MyFrame() {
            TextField textField = new TextField();
            add(textField);
    
            // 监听这个文本框输入的文字
            MyActionListebter2 myActionListebter2 = new MyActionListebter2();
            //按下enter ,就会触发这个输入框的事件
            textField.addActionListener(myActionListebter2);
    
            // 设置替换编码
            textField.setEchoChar('*');
            pack();
            setVisible(true);
    
        }
    }
    
    class MyActionListebter2 implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            TextField field = (TextField) e.getSource(); //获得一些资源 返回一个对象
            System.out.println(field.getText());
            field.setText(""); // 清空操作
        }
    }
    

    6.简易计算机。组合+内部类回顾复习

    oop原则:组合 大于继承!

    public class Calculate {
        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);
    
            // 1个按钮
            Button button = new Button("=");
            button.addActionListener(new MyCalculatorListener(this));
            // 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;
        // 获取计算器这个对象,在一个类中组合另外一个类
        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("");
        }
    }
    

    内部类 :更好的包装

    public class Calculate {
        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);
    
            // 1个按钮
            Button button = new Button("=");
            button.addActionListener(new MyCalculatorListener());
            // 1个标签
            Label label = new Label("+");
    
            // 布局
            setLayout(new FlowLayout());
            add(num1);
            add(label);
            add(num2);
            add(button);
            add(num3);
    
            pack();
            setVisible(true);
    
        }
        private class MyCalculatorListener implements ActionListener {
            // 获取三个变量
            //private TextField num1, num2, 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("");
            }
        }
    
    }
    

    自己版

    public class Calculator {
        public static void main(String[] args) {
            new cal().init();
        }
    }
    class cal extends Frame {
    
        TextField num1, num2, num3;
        Button button;
        Label label;
        public void init() {
            num1 = new TextField(10);
            num2  = new TextField(10);
            num3  = new TextField(20);
    
            button = new Button("=");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    num3.setText(""+(Integer.parseInt(num1.getText())+ Integer.parseInt(num2.getText())));
                    num1.setText("");
                    num2.setText("");
                }
            });
            label = new Label("+");
    
            setLayout(new FlowLayout());
            add(num1);
            add(label);
            add(num2);
            add(button);
            add(num3);
    
            pack();
            setVisible(true);
        }
    

    7.画笔

    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) {
           // super.paint(g);
           // g.setColor(Color.red);
            g.fillOval(100,100,100,100);
            //  g.setColor(Color.green);
            g.fillRect(200,200,200,200);
            //repaint();
        }
    }
    

    8.鼠标监听

    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,600,500);
            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.pink);
                g.fillOval(point.x, point.y,10,10);
            }
        }
    
        // 添加一个点到界面上
        public void addPaint(Point point) {
            points.add(point);
        }
    
       //适配器模式
        // 如果用接口则需要重写所有方法,但是用继承则可以完好的避免  这就是适配器模式9
        private class MyMouseListener extends MouseAdapter {
            // 按下  按住不放, 弹起
            public void mousePressed(MouseEvent e) { // 获取鼠标资源
                MyFrame frame = (MyFrame) e.getSource();
                // 这里我们点击的时候就会在界面上产生=一个点
                // 这个点就是鼠标的点
                frame.addPaint(new Point(e.getX(), e.getY()));
    
                // 每次点击鼠标都需要重画一遍
                frame.repaint(); // 刷新 30hz  60hz
            }
        }
    }
    

    9.窗口监听

    public class Testwindow {
        public static void main(String[] args) {
            new WindowFrame();
        }
    }
    class WindowFrame extends Frame{
        public WindowFrame() {
    
            setBackground(Color.pink);
            setBounds(100,100,200,300);
    
            setVisible(true);
    
            this.addWindowListener(new WindowAdapter() {
    
                @Override
                public void windowActivated(WindowEvent e) {
                    WindowFrame source = (WindowFrame) e.getSource();
                    source.setTitle("被激活了");
                    System.out.println("windowActivated");
                }
    
                @Override
                public void windowClosing(WindowEvent e) {
                    System.out.println("windowClosing");
    
                }
            });
    
        }
    
    //    class MyWindowListener extends WindowAdapter {
    //        @Override
    //        public void windowClosing(WindowEvent e) {
    //            setVisible(false); // 隐藏窗口  ,通过按钮, 隐藏当前窗口
    //            System.exit(0); // 正常退出
    //        }
    //    }
    }
    

    10.键盘监听

    public class TestKeyListener {
        public static void main(String[] args) {
            new MyFrame1();
        }
    }
    class MyFrame1 extends Frame {
        public MyFrame1() {
            super();
            setBounds(100,200,300,400);
            setVisible(true);
    
            addKeyListener(new KeyAdapter() {
                // 键盘按下
                @Override
                public void keyPressed(KeyEvent e) {
                // 键盘按下的键是哪一个,  当前的代码
                    int keyCode = e.getKeyCode();
                    System.out.println(keyCode);
                    if (keyCode == KeyEvent.VK_UP) {
                        System.out.println("你按下了上键");
                    }
                }
            });
        }
    }
    

    3. Swing


    1.窗口,面板

    public class JFrameDemo extends JFrame{
    
        // 初始化
        public void init() {
            // 顶级窗口
            JFrame jFrame = new JFrame("这是一个Jframe窗口");
            jFrame.setVisible(true);
            jFrame.setBounds(100,100,200,200);
            jFrame.setBackground(Color.BLACK);
    
            // 设置文字
            JLabel jLabel = new JLabel("欢迎来到  杰杰的世界");
            jFrame.add(jLabel);
    
    
            // 容器实例化
    
            // 关闭事件
            jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
        }
    
        public static void main(String[] args) {
            // 建立一个方法
            new JFrameDemo().init();
        }
    }
    

    2.弹窗

    // 主窗口
    public class Dialog extends JFrame {
    
        public void init() {
            this.setVisible(true);
            this.setSize(700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            // 放东西需要容器
            Container container = this.getContentPane();
            // 绝对布局
            container.setLayout(null);
            // 按钮
            JButton jButton = new JButton("点击弹出一个对话框");
            jButton.setBounds(30,30,200,50);
            jButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 弹窗
                    new MyDialog();
                }
            });
    
    
            container.add(jButton);
    
    
    
        }
        public static void main(String[] args) {
            new Dialog().init();
        }
    }
    // 弹窗的窗口
    class MyDialog extends JDialog {
        public MyDialog() {
            this.setVisible(true);
            this.setBounds(100,100,500,500);
    //        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);   弹窗默认
    
            Container container = this.getContentPane();
            container.setLayout(null);
            JLabel jLabel = new JLabel("liyujie jie jie jie jie ");
            jLabel.setBounds(50,50,200,200);
            container.add(jLabel);
        }
    

    3.标签

    图标

    // 图标, 需要实现类
    public class IcnoDemo extends JFrame implements Icon {
    
        private int width;
        private int height;
    
        public IcnoDemo() {
        } // 无参构造
    
        public IcnoDemo(int width, int height) throws HeadlessException {
            this.width = width;
            this.height = height;
        }
    
        public void init() {
            IcnoDemo icnoDemo = new IcnoDemo(15, 15);
            // 图标放在标签  按钮
            JLabel jLabel = new JLabel("icontest",icnoDemo, SwingConstants.CENTER);
    
            Container container = getContentPane();
            container.add(jLabel);
    
            this.pack();
            this.setVisible(true);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
    
        }
    
    
    
        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            g.fillOval(x,y,width,height);
        }
    
        @Override
        public int getIconWidth() {
            return this.width;
        }
    
        @Override
        public int getIconHeight() {
            return this.height;
        }
    
    
    
    
        public static void main(String[] args) {
            new IcnoDemo().init();
        }
    }
    

    图片

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

    4.面板

    JPanel

    public class JPanelDemo extends JFrame {
    
        public JPanelDemo() {
            Container container = this.getContentPane();
    
            container.setLayout(new GridLayout(2,3,10,10));
    
            JPanel jPanel = new JPanel(new GridLayout(1,3));
            JPanel jPanel2 = new JPanel(new GridLayout(1,2));
            JPanel jPanel3 = new JPanel(new GridLayout(2,1));
            JPanel jPanel4 = new JPanel(new GridLayout(3,2));
    
            jPanel.add(new JButton("1"));
            jPanel.add(new JButton("1"));
            jPanel.add(new JButton("1"));
            container.add(jPanel);
    
            jPanel2.add(new JButton("2"));
            jPanel2.add(new JButton("2"));
            container.add(jPanel2);
    
            jPanel3.add(new JButton("3"));
            jPanel3.add(new JButton("3"));
            container.add(jPanel3);
    
            jPanel4.add(new JButton("4"));
            jPanel4.add(new JButton("4"));
            jPanel4.add(new JButton("4"));
            jPanel4.add(new JButton("4"));
            jPanel4.add(new JButton("4"));
            jPanel4.add(new JButton("4"));
            container.add(jPanel4);
    
            this.setVisible(true);
            this.setSize(500,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new JPanelDemo();
        }
    }
    

    JScroll

    public class JScrollDemo extends JFrame {
        public JScrollDemo() {
            Container container = this.getContentPane();
    
            JTextArea textArea = new JTextArea(20,50);
            textArea.setText("欢迎来到杰杰的世界");
    
            JScrollPane jScrollPane = new JScrollPane(textArea);
    
            container.add(jScrollPane);
    
    
            this.setVisible(true);
            this.setBounds(100,100,700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
    
        public static void main(String[] args) {
            new JScrollDemo();
        }
    }
    

    5.按钮

    public class JButtonDemo01 extends JFrame {
    
        public JButtonDemo01() {
            Container container = this.getContentPane();
            URL url = JButtonDemo01.class.getResource("666.png");
            Icon icon = new ImageIcon(url); // 将一个图片变为图标
    
            // 把图标放在按钮上
            JButton jButton = new JButton();
            jButton.setIcon(icon);
            jButton.setToolTipText("图片按钮");
    
    
            container.add(jButton);
    
            this.setVisible(true);
            this.setBounds(100,100,700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
    
        }
    
        public static void main(String[] args) {
            new JButtonDemo01();
        }
    }
    

    ​ 单选按钮

    public class JButtonDemo01 extends JFrame {
    
        public JButtonDemo01() {
            Container container = this.getContentPane();
            URL url = JButtonDemo01.class.getResource("666.png");
            Icon icon = new ImageIcon(url); // 将一个图片变为图标
    
            //单选框
            JRadioButton radioButton1 = new JRadioButton("1");
            JRadioButton radioButton2 = new JRadioButton("2");
            JRadioButton radioButton3 = new JRadioButton("3");
    
            // 单选框只能选择一个,分组
            ButtonGroup group = new ButtonGroup();
            group.add(radioButton1);
            group.add(radioButton2);
            group.add(radioButton3);
    
            container.add(radioButton1, BorderLayout.CENTER);
            container.add(radioButton2, BorderLayout.SOUTH);
            container.add(radioButton3, BorderLayout.NORTH);
    ;
    
            this.setVisible(true);
            this.setBounds(100,100,700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
    
        }
    
        public static void main(String[] args) {
            new JButtonDemo01();
        }
    }
    

    ​ 复选按钮

    public class JButtonDemo01 extends JFrame {
    
        public JButtonDemo01() {
            Container container = this.getContentPane();
            URL url = JButtonDemo01.class.getResource("666.png");
            Icon icon = new ImageIcon(url); // 将一个图片变为图标
    
            // 多选框
            JCheckBox checkBox1 = new JCheckBox("1");
            JCheckBox checkBox2 = new JCheckBox("2");
            JCheckBox checkBox3 = new JCheckBox("3");
    
            container.add(checkBox1,BorderLayout.NORTH);
            container.add(checkBox2, BorderLayout.CENTER);
            container.add(checkBox3, BorderLayout.SOUTH);
    
            this.setVisible(true);
            this.setBounds(100,100,700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
    
        }
    
        public static void main(String[] args) {
            new JButtonDemo01();
        }
    }
    

    6.列表

    下拉框

    public class TestComboboxDemo01 extends JFrame {
        public TestComboboxDemo01() {
            Container container = this.getContentPane();
    
            JComboBox comboBox = new JComboBox();
            comboBox.addItem(null);
            comboBox.addItem("正在上映");
            comboBox.addItem("已下架");
            comboBox.addItem("即将上映");
    
    
            container.add(comboBox);
    
            this.setVisible(true);
            this.setBounds(100,100,700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
        }
    
        public static void main(String[] args) {
            new TestComboboxDemo01();
        }
    }
    

    列表框

    public class TestComboBoxDemo02 extends JFrame{
        public TestComboBoxDemo02() {
            Container container = this.getContentPane();
    
    
            //生成列表内容
            //String[] contents = {"1", "2", "3"};
    
            Vector contents = new Vector();
            //列表中放内容
            JList list = new JList(contents);
            contents.add("liyujie");
            contents.add("Richard");
            contents.add("lichade");
            contents.add("dajshdksu");
    
    
            container.add(list);
    
            this.setVisible(true);
            this.setBounds(100,100,700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
        }
    
        public static void main(String[] args) {
            new TestComboBoxDemo02();
    
        }
    }
    

    7. 文本框

    展开全文
  • Java GUI编程

    2020-11-10 20:52:09
    GUI编程 主要学习一些组件的使用 包括: 窗口 弹窗 面板 文本框 列表框 按钮 图片 监听事件 鼠标 键盘事件 1. 简介 GUI的核心技术:Swing,AWT 没流行的原因:不美观,需要jre环境 作用: 写自己的小工具 维护...

    GUI编程

    主要学习一些组件的使用

    包括:

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

    1. 简介

    GUI的核心技术:Swing,AWT

    没流行的原因:不美观,需要jre环境

    作用:

    1. 写自己的小工具
    2. 维护swing界面
    3. 了解MVC架构,了解监听

    2. AWT

    2.1 概述

    Abstract window toolkit

    1. 包含了很多类和接口,GUI(graphical user interface),图形用户界面

    2. 元素:窗口,按钮,文本框

    3. java.awt

    2.2 组件和容器

    1. Frame框架

    package com.chao.lesson01;
    
    import java.awt.*;
    
    //GUI的第一个界面
    public class TestFrame {
        public static void main(String[] args) {
            //只有这个是看不见的,不可见
            Frame frame = new Frame("我的第一个Java图像界面窗口");
    
            //设置可见性
            frame.setVisible(true);
    
            //设置窗口大小
            frame.setSize(400,400);
    
            //设置颜色
            frame.setBackground(new Color(58, 16,89));
    
            //初始位置
            frame.setLocation(200,200);
    
            //设置大小固定
            frame.setResizable(false);
    
        }
    }
    
    

    进行了一些封装的

    package com.chao.lesson01;
    
    import java.awt.*;
    
    public class TestFrame2 {
        public static void main(String[] args) {
            new MyFrame(100,100,200,200,Color.red);
            new MyFrame(300,100,200,200,Color.green);
            new MyFrame(100,300,200,200,Color.yellow);
            new MyFrame(300,300,200,200,Color.blue);
    
    
        }
    
    }
    class MyFrame extends Frame {
        static int id = 0;
    
        public MyFrame(int x, int y, int w, int h, Color color) {
            super("Myframe"+(++id));
            setVisible(true);
            setSize(w,h);
            setLocation(x,y);
            setBackground(color);
    
        }
    }
    
    

    2. Panel面板

    可以看成一个空间,但是不能单独存在

    package com.chao.lesson01;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    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,5));
    
            //面板的,相对于frame
            panel.setBounds(50,50,400,400);
            panel.setBackground(new Color(80, 26, 11));
    
            frame.add(panel);
            frame.setVisible(true);
    
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    
    

    2.3 布局管理器

    1. 流式布局

    package com.chao.lesson02;
    
    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(FlowLayout.CENTER));//默认值
    //        frame.setLayout(new FlowLayout(FlowLayout.LEFT));//左对齐
            frame.setLayout(new FlowLayout(FlowLayout.RIGHT));//右对齐
            frame.setSize(200,200);
    
            frame.add(button1);
            frame.add(button2);
            frame.add(button3);
            frame.setVisible(true);
    
        }
    
    }
    

    2. 边界布局(东西南北中)

    package com.chao.lesson02;
    
    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");
            frame.setSize(200,200);
            frame.setLayout(new BorderLayout());
    
            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.setVisible(true);
    
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
    
        }
    }
    
    

    3. 表格布局

    package com.chao.lesson02;
    
    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 com.chao.lesson02;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    public class TestNew {
        public static void main(String[] args) {
    
            Frame frame = new Frame();
            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("btn1"),BorderLayout.WEST);
            p1.add(new Button("btn2"),BorderLayout.EAST);
            p2.add(new Button("1"));
            p2.add(new Button("2"));
            p1.add(p2,BorderLayout.CENTER);
    
            p3.add(new Button("btn3"),BorderLayout.WEST);
            p3.add(new Button("btn4"),BorderLayout.EAST);
            for(int i = 0; i<4;i++){
                p4.add(new Button("new"+(++i)));
            }
            p3.add(p4,BorderLayout.CENTER);
    
    
            frame.add(p1,BorderLayout.NORTH);
            frame.add(p3,BorderLayout.SOUTH);
            frame.pack();
    
            frame.setVisible(true);
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
    
        }
    
    }
    
    

    2.4 事件监听

    某个事件发生,进行一些处理

    1. 基础的按键监听
    package com.chao.lesson03;
    
    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 TestAction {
        public static void main(String[] args) {
            Frame frame = new Frame();
            Button button = new Button();
    
            MyActionListener myActionListener = new MyActionListener();
            button.addActionListener(myActionListener);
    
            frame.add(button,BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
    
            windowClose(frame);
    
        }
    
        private static void windowClose(Frame frame){
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    
    class MyActionListener implements ActionListener {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("aaa");
        }
    }
    
    

    两个按钮同时的监听,多个按钮共享一个事件

    package com.chao.lesson03;
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class TestActionTwo {
        public static void main(String[] args) {
            //两个按钮,实现同一个监听
            Frame frame = new Frame("stat-stop test");
            Button button1 = new Button("start");
            Button button2 = new Button("stop");
    
            //如果不设置,默认就是标签名
            button2.setActionCommand("设置过了的stop");
    
    
            MyListener myListener = new MyListener();
            button1.addActionListener(myListener);
            button2.addActionListener(myListener);
    
    
    
            frame.add(button1,BorderLayout.NORTH);
            frame.add(button2,BorderLayout.SOUTH);
            frame.setVisible(true);
            frame.pack();
        }
    }
    
    class MyListener implements ActionListener {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("msg=>" + e.getActionCommand());
        }
    }
    
    

    2.5 输入框监听

    package com.chao.lesson03;
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class TestText {
        //main函数是入口,只有启动功能
        public static void main(String[] args) {
            MyFrame myFrame = new MyFrame();
    
        }
    }
    
    class MyFrame extends Frame{
        MyFrame(){
            TextField textField = new TextField();
            add(textField);
    
            //监听这个文本框的文字
            TextListener textListener = new TextListener();
            //按下enter就会触发这个输入框的事件
            textField.addActionListener(textListener);
    
            //设置显示格式
            textField.setEchoChar('$');
    
            setVisible(true);
            pack();
    
        }
    
    
    }
    
    class TextListener implements ActionListener{
    
        @Override
        public void actionPerformed(ActionEvent e) {
            TextField t = (TextField) e.getSource();//获得资源,返回值类型为Object
            System.out.println(t.getText());//获得输入框的文本
            t.setText("");//回车后变空
        }
    }
    
    

    2.6 简易计算器

    面向对象编程的原则:组合,大于继承

    class A{
        public B b;
    }
    

    1. 普通版

    package com.chao.lesson03;
    
    import javax.swing.text.html.InlineView;
    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 TestCalc {
        public static void main(String[] args) {
            Calculator calculator = new Calculator();
    
    
        }
    }
    
    //计算器类
    class Calculator extends Frame {
        public Calculator()  {
            setLayout(new FlowLayout());
            //3个文本框
            TextField sum1 = new TextField(10);
            TextField sum2 = new TextField(10);
            TextField ret = new TextField(20);
    
            //1个按钮
            Button sign = new Button("=");
            sign.addActionListener(new MyCalcListener(sum1,sum2,ret));
    
            //1个标签
            Label label = new Label("+");
    
            add(sum1);
            add(label);
            add(sum2);
            add(sign);
            add(ret);
    
    
    
            setVisible(true);
            pack();
    
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
        }
    }
    
    //监听器类
    class MyCalcListener implements ActionListener{
        private TextField sum1,sum2,ret;
    
        public MyCalcListener(TextField sum1,TextField sum2,TextField ret) {
            this.sum1 =sum1;
            this.sum2 =sum2;
            this.ret =ret;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
    
            //1.获得两个数
            int n1 = Integer.parseInt(sum1.getText());
            int n2 = Integer.parseInt(sum2.getText());
    
            //2.执行加法操作
            ret.setText(""+(n1+n2));
    
            //3.清除前两个数
            sum1.setText("");
            sum2.setText("");
    
        }
    }
    
    

    2. 组合

    package com.chao.lesson03;
    
    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 TestCalc01 {
        public static void main(String[] args) {
            //启动
            new Calculator01().load();
    
        }
    }
    
    //计算器类
    class Calculator01 extends Frame {
        //属性
        TextField sum1,sum2,ret;
    
        //方法
        public void load(){
            setLayout(new FlowLayout());
            //3个文本框
            sum1 = new TextField(10);
            sum2 = new TextField(10);
            ret = new TextField(20);
    
            //1个按钮
            Button sign = new Button("=");
            sign.addActionListener(new MyCalcListener01(this));
    
            //1个标签
            Label label = new Label("+");
    
            add(sum1);
            add(label);
            add(sum2);
            add(sign);
            add(ret);
    
            setVisible(true);
            pack();
    
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
        }
    
    }
    
    //监听器类
    class MyCalcListener01 implements ActionListener{
        //获取计算器这个对象,在一个类中组合另一个类
        Calculator01 calculator01 = null;
    
        public MyCalcListener01(Calculator01 calculator01) {
            this.calculator01  = calculator01;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
    
            //1.获得两个数
            int n1 = Integer.parseInt(calculator01.sum1.getText());
            int n2 = Integer.parseInt(calculator01.sum2.getText());
    
            //2.执行加法操作
            calculator01.ret.setText(""+(n1+n2));
    
            //3.清除前两个数
            calculator01.sum1.setText("");
            calculator01.sum2.setText("");
    
        }
    }
    

    3. 内部类(还要练习)

    面向对象,内部类的最大好处,就是可以畅通无阻的访问外部类的属性和方法。

    package com.chao.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 TestCalc {
        public static void main(String[] args) {
            new Calculator().loadCalc();
        }
    
    }
    
    class Calculator extends Frame{
        //属性
        TextField num1,num2,num3;
    
        //方法
        public void loadCalc(){
            //3个文本框
            num1 = new TextField(10);
            num2 = new TextField(10);
            num3 = new TextField(20);
    
            //1个标签
            Label label = new Label("+");
    
            //1个按钮
            Button button = new Button("=");
            button.addActionListener(new MyCalListener());
    
            setLayout(new FlowLayout());
            add(num1);
            add(label);
            add(num2);
            add(button);
            add(num3);
    
            setVisible(true);
            pack();
    
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    
        class MyCalListener 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.7 画笔

    package com.chao.GUI;
    
    import java.awt.*;
    
    public class TestPaint {
        public static void main(String[] args) {
            new MyPaint();
        }
    }
    class MyPaint extends Frame {
        MyPaint(){
            setBounds(100,100,500,600);
            setVisible(true);
        }
    
        //画笔
        @Override
        public void paint(Graphics g) {
    //        super.paint(g);
            //设置画笔颜色
            g.setColor(Color.red);
            //画空心圆
            g.drawOval(100,100,100,100);
            //换颜色
            g.setColor(Color.green);
            //填充圆
            g.fillOval(150,200,100,100);
            //画矩形
            g.fillRect(200,300,100,100);
    
            //画笔默认颜色是黑色,所以每次用完将它还原
    
        }
    }
    

    2.8 鼠标监听

    目的:实现鼠标画画

    package com.chao.GUI;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    
    
    //鼠标监听事件
    public class TestMouse {
        public static void main(String[] args) {
            MyMouse myMouse = new MyMouse("MyMouse-画图");
        }
    }
    
    
    //鼠标类
    class MyMouse extends Frame{
        //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这些点
        ArrayList points;//存位置的
    
        public MyMouse(String title) {
            super(title);
            setBounds(100,100,400,300);
    
            //存鼠标的位置的点
            points = new ArrayList<>();
            //鼠标监听器,针对这个窗口
            this.addMouseListener(new MyMouseListener());
            setVisible(true);
    
            this.addWindowListener(new MyWindowListener());
    
        }
    
        @Override
        public void paint(Graphics g) {
            //画画,需要监听鼠标的事件(因为鼠标在哪画在哪
            Iterator iterator = points.iterator();
            while (iterator.hasNext()){
                Point point =(Point)iterator.next();
                g.setColor(Color.green);
                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) {
                MyMouse myMouse = (MyMouse) e.getSource();
                //点击的时候,产生一个点,画出来
    
                //这个点就是鼠标的点
                myMouse.addPaint(new Point(e.getX(),e.getY()));
    
                //每次点击鼠标都要重画一遍
                myMouse.repaint();//刷新
            }
        }
        private class MyWindowListener extends WindowAdapter{
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        }
    
    }
    
    
    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;
    import java.util.List;
    
    //测试鼠标监听
    public class TestMouseListenter {
        public static void main(String[] args) {
            new Paint("画图").loadMyPaint();
        }
    }
    class Paint extends Frame {
        private List<Point> pointList;
        private Paint cuttorPaint;
        public Paint(String title){
            super(title);
            cuttorPaint = this;
            pointList = new ArrayList<>();
        }
        public void loadMyPaint(){
            setVisible(true);
            setBounds(100,100,800,600);
            addMouseListener(new MyMouseListenter());
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    
        @Override
        public void paint(Graphics g) {
            Iterator<Point> iterator = pointList.iterator();
            while (iterator.hasNext()){
                Point point = iterator.next();
                //循环画列表的点坐标
                g.fillOval(point.x,point.y,10,10);
            }
        }
        private class MyMouseListenter extends MouseAdapter{
    //        按下鼠标时触发
            @Override
            public void mousePressed(MouseEvent e) {
                pointList.add(new Point(e.getX(),e.getY()));
                //画笔重新画点
                cuttorPaint.repaint();
            }
        }
    }
    
    

    [https://blog.csdn.net/u011412779/article/details/106629686/?biz_id=102&utm_term=GUI%E7%8B%82%E7%A5%9E&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-106629686&spm=1018.2118.3001.4449]摘自以上

    2.9 窗口监听

    内部类

    package com.chao.GUI;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    public class TestWindow {
        public static void main(String[] args) {
            new MyWindow();
        }
    }
    
    class MyWindow extends Frame{
        public MyWindow(){
            setBounds(100,100,400,300);
            setVisible(true);
            addWindowListener(new MyWindowListener());
    
        }
        class MyWindowListener extends WindowAdapter{
            @Override
            public void windowClosing(WindowEvent e) {
    
                setVisible(false);//隐藏窗口,使不可见
                System.exit(0);
            }
        }
    }
    
    
    
    

    使用匿名内部类

    package com.chao.GUI;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    public class TestWindow {
        public static void main(String[] args) {
            new MyWindow();
        }
    }
    
    class MyWindow extends Frame{
        public MyWindow(){
            setBounds(100,100,400,300);
            setVisible(true);
    //        addWindowListener(new MyWindowListener());
            this.addWindowListener(
                    //匿名内部类
                    new WindowAdapter() {
    
                        //关闭
                        @Override
                        public void windowClosing(WindowEvent e) {
                            System.out.println("你点了x");
                            System.exit(0);
                        }
                        //激活
                        @Override
                        public void windowActivated(WindowEvent e) {
                            MyWindow myWindow = (MyWindow)e.getSource();
                            myWindow.setTitle("被激活了");
                        }
    
    
                    }
            );
    
        }
    }
    
    
    
    

    2.10 键盘监听

    package com.chao.GUI;
    
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    
    public class TestKey {
        public static void main(String[] args) {
            new MyKey();
        }
    }
    
    class MyKey extends Frame {
        public MyKey(){
            setBounds(100,200,400,300);
            setVisible(true);
    
            this.addKeyListener(
                    new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent e) {
                            //获得键盘的键是哪一个,是当前的码
                            int keyCode = e.getKeyCode();
                            System.out.println(keyCode);
                            if(keyCode== KeyEvent.VK_W){
                                System.out.println("你按了w");
                            }
                        }
                    }
            );
    
        }
    }
    
    

    3. Swing

    3.1 JFrame 窗口

    package com.chao.GUI.lesson02;
    
    import sun.security.krb5.internal.tools.Kinit;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class JFrameDemo {
        //init初始化
        public void init(){
            //顶级窗口
            JFrame jf= new JFrame("第一个JFrame窗口");
            jf.setVisible(true);
            jf.setBounds(100,100,400,300);
            jf.setBackground(Color.green);//没有用,因为要使用容器,需要实例化
    
            //获得一个容器,不用容器设置不了颜色
            Container container = jf.getContentPane();//返回值是container
            container.setBackground(Color.green);
    
            //设置文字
            JLabel jLabel = new JLabel("欢迎来到新世界");
            jf.add(jLabel);
            //居中显示
            jLabel.setHorizontalAlignment(SwingConstants.CENTER);
    
            jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new JFrameDemo().init();
        }
    }
    
    

    3.2 JDialog 弹窗

    package com.chao.GUI.lesson02;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class JDialogDemo extends JFrame {
        public JDialogDemo(){
            this.setVisible(true);
            this.setBounds(100,100,400,300);
            //自动关闭
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
    
            //容器,放东西
            Container container =this.getContentPane();
            //绝对布局,使用x,y坐标
            container.setLayout(null);
    
            JButton jButton = new JButton("点击就弹窗");
            jButton.setBounds(30,30,100,100);
            container.add(jButton);
            jButton.addActionListener(
                    new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            new MyDialog();
                        }
                    }
            );
    
        }
    
        public static void main(String[] args) {
    
            new JDialogDemo();
        }
    }
    
    class MyDialog extends JDialog{
        public MyDialog(){
            this.setTitle("第一个弹窗");
            this.setVisible(true);
            this.setBounds(100,100,300,300);
            this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    
            Container container =this.getContentPane();
            container.setLayout(null);
            JLabel jLabel = new JLabel("欢迎来到王颖超的世界");
            jLabel.setBounds(20,20,200,100);
            container.add(jLabel);
        }
    
    }
    

    3.3 标签

    JLabel

    图标Icon

    package com.chao.GUI.lesson02;
    
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    
    public class ImageIconTest extends JFrame {
    
        public ImageIconTest(){
            JLabel jLabel = new JLabel("ImageIcon");
            //获取图片地址
            URL url = ImageIconTest.class.getResource("tp.jpg");
    
            //借助标签
            ImageIcon imageIcon = new ImageIcon(url);
            jLabel.setIcon(imageIcon);
            jLabel.setHorizontalAlignment(SwingConstants.CENTER);
    
            Container container = getContentPane();
            container.add(jLabel);
    
            setVisible(true);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setBounds(100,100,700,700);
    
    
    
        }
        public static void main(String[] args) {
            new ImageIconTest();
    
        }
    }
    
    

    3.4 面板

    JPanel

    package com.chao.GUI.lesson02;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class JPanelDemo extends JFrame {
        public static void main(String[] args) {
            new JPanelDemo();
        }
    
        public JPanelDemo(){
            this.setVisible(true);
            this.setBounds(100,100,500,400);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            JPanel panel1 = new JPanel(new GridLayout(3,1));
            JPanel panel2 = new JPanel(new GridLayout(1,2));
            JPanel panel3 = new JPanel(new GridLayout(2,2));
            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"));
            panel3.add(new JButton("3"));
            panel3.add(new JButton("3"));
            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 container = getContentPane();
            //行数与列数必须设置,不然会出现格式错误
            //另外,当设置的行数与列数乘积大于面板数,会空出一些区域
            //当设置的行数与列数乘积小于面板数,会自动扩大区域
            //后两个参数是间距
            container.setLayout(new GridLayout(3,2,15,15));
            container.add(panel1);
            container.add(panel2);
            container.add(panel3);
            container.add(panel4);
        }
    
    }
    

    滑动JScroll

    package com.chao.lesson03;
    
    import com.sun.deploy.panel.ControlPanel;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class JScrollTest extends JFrame {
    
        public static void main(String[] args) {
            new JScrollTest();
    
        }
    
        public JScrollTest() {
            this.setVisible(true);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            this.setBounds(100,100,500,400);
    
            Container container =this.getContentPane();
    
            JTextArea jtextArea = new JTextArea("你好呀",30,20);
            jtextArea.setText("我好了");
            JScrollPane jScrollPane = new JScrollPane(jtextArea);
            container.add(jScrollPane);
        }
    }
    
    

    3.5 按钮

    图片按钮

    package com.chao.lesson03;
    
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    
    public class JButtonDemo01 extends JFrame {
        public JButtonDemo01(){
            this.setVisible(true);
            this.setBounds(100,100,500,400);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            Container container = getContentPane();
    
            //将图片变成图标
            URL url=JButtonDemo01.class.getResource("test.jpg");
            ImageIcon imageIcon = new ImageIcon(url);
    
            //把图标加到按钮上
            JButton jbutton = new JButton(imageIcon);
            container.add(jbutton);
            pack();
        }
    
        public static void main(String[] args) {
            new JButtonDemo01();
        }
    
    }
    
    • 单选按钮
    package com.chao.lesson03;
    
    import javafx.scene.control.RadioButton;
    
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    
    public class JButtonDemo02 extends JFrame {
        public JButtonDemo02(){
            this.setVisible(true);
            this.setBounds(100,100,500,400);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            //单选框JRadioButton
            Container container = getContentPane();
            JRadioButton jRadioButton1 = new JRadioButton("JRadioButton1");
            JRadioButton jRadioButton2 = new JRadioButton("JRadioButton2");
            JRadioButton jRadioButton3 = new JRadioButton("JRadioButton3");
    
            //通过分组的形式实现单选框只能选择一个的操作
            ButtonGroup buttonGroup = new ButtonGroup();
            buttonGroup.add(jRadioButton1);
            buttonGroup.add(jRadioButton2);
            buttonGroup.add(jRadioButton3);
    
            //设置位置
            container.add(jRadioButton1,BorderLayout.CENTER);
            container.add(jRadioButton2,BorderLayout.SOUTH);
            container.add(jRadioButton3,BorderLayout.NORTH);
            pack();
    
        }
    
        public static void main(String[] args) {
            new JButtonDemo02();
        }
    }
    
    
    • 复选按钮
    package com.chao.lesson03;
    
    import javafx.scene.control.RadioButton;
    
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    
    public class JButtonDemo03 extends JFrame {
        public JButtonDemo03(){
            this.setVisible(true);
            this.setBounds(100,100,500,400);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            //多选框
            Checkbox checkBox1 = new Checkbox("CheckBox1");
            Checkbox checkBox2 = new Checkbox("CheckBox2");
    
            Container container = getContentPane();
    
            container.add(checkBox1,BorderLayout.NORTH);
            container.add(checkBox2,BorderLayout.SOUTH);
            pack();
    
    
        }
    
        public static void main(String[] args) {
            new JButtonDemo03();
        }
    }
    
    

    3.6 列表

    下拉框

    package com.chao.lesson03;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class JComboBoxDemo extends JFrame {
        public static void main(String[] args) {
            new JComboBoxDemo();
    
        }
    
        public JComboBoxDemo(){
            this.setVisible(true);
            this.setBounds(100,100,500,400);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            JComboBox option = new JComboBox();
            option.addItem("正在热映");
            option.addItem("已下线");
            option.addItem("即将上映");
    
            Container container = getContentPane();
            container.add(option);
        }
    }
    
    

    列表框

    package com.chao.lesson03;
    
    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    
    public class JBoxDemo extends JFrame {
        public static void main(String[] args) {
            new JBoxDemo();
        }
    
        public JBoxDemo(){
            this.setVisible(true);
            this.setSize(500,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            //这一行要往前放,不然容易第一次加载不出来内容
            Container container = getContentPane();
    
    //        //生成列表的内容
    //        String[] arr = {"1","2","3"};
    //
    //        //将内容放入列表
    //        JList jList = new JList(arr);
            //也可以放Vector
            Vector content = new Vector();
    
            content.add("zhangsan");
            content.add("lisi");
            content.add("wangwu");
            content.remove("wangwu");
            JList jList = new JList(content);
    
    
            container.add(jList);
    
        }
    }
    
    

    应用场景

    1. 一些单个选项。少于两个用单选框,多于两个用下拉框

    2. 列表框用于展示一些信息,一般可以动态扩容(add,remove)

    3.7 文本框

    普通文本框

    package com.chao.lesson03;
    
    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    
    public class JBoxDemo extends JFrame {
        public static void main(String[] args) {
            new JBoxDemo();
        }
    
        public JBoxDemo(){
            this.setVisible(true);
            this.setSize(500,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            //这一行要往前放,不然容易第一次加载不出来内容
            Container container = getContentPane();
    
    //        //生成列表的内容
    //        String[] arr = {"1","2","3"};
    //
    //        //将内容放入列表
    //        JList jList = new JList(arr);
            //也可以放Vector
            Vector content = new Vector();
    
            content.add("zhangsan");
            content.add("lisi");
            content.add("wangwu");
            content.remove("wangwu");
            JList jList = new JList(content);
    
    
            container.add(jList);
    
        }
    }
    
    

    密码框

    package com.chao.lesson03;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class JTextDemo2 extends JFrame {
        public static void main(String[] args) {
            new JTextDemo2();
        }
    
        public JTextDemo2(){
            Container container = getContentPane();
    
            JPasswordField jPasswordField = new JPasswordField();//默认使用·进行隐藏
            jPasswordField.setEchoChar('¥');//被钱迷惑了双眼
    
            container.add(jPasswordField);
    
    
    
    
            this.setVisible(true);
            this.setSize(500,400);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
        }
    }
    

    文本域 JTextArea,讲JScroll时

    ps:

    HTML,Servlet,MVC

    C/S:Client/Server,客户端和服务器

    B/S:Browser/Server,浏览器和服务器

    贪吃蛇

    GamePage

    package com.chao.GUI.snakegame;
    
    import javax.swing.*;
    
    public class GamePage extends JFrame {
    
        public void init(){
    
            //开始了解为什么要把设置可见性的这些代码放在最后,不然容易出现监听失败等问题,初始加载不全
            this.add(new GamePanel());
    
    
            this.setVisible(true);
            this.setBounds(15,10,920,740);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            this.setResizable(false);
        }
    
        public static void main(String[] args) {
            new GamePage().init();
        }
    
    }
    
    

    GamePanel

    package com.chao.GUI.snakegame;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Random;
    
    public class GamePanel extends JPanel implements KeyListener, ActionListener {
        //定义蛇的数据结构
        int length;//蛇的长度
        int[] snakeX = new int[600];//x坐标
        int[] snakeY = new int[600];//y坐标
        String direction;//初始方向向右
        Boolean isStart;//记录游戏的状态
        Boolean isFail;//记录失败的状态
        int foodx;
        int foody;
        int score;
        Random random = new Random();
    
        //定时器,以ms为单位,表示没多少毫秒执行一次
        Timer timer = new Timer(100,this);
    
        //初始化蛇
        public void init(){
            length = 3;
            snakeX[0] = 100;snakeY[0]=100;//头部初始位置
            snakeX[1] = 75;snakeY[1]=100;//第一节身体初始位置
            snakeX[2] = 50;snakeY[2]=100;//第二节身体初始位置
            direction = "R";//默认向右
            isStart = false;//默认不开始
            isFail = false;//默认不失败
            score = 0;
            timer.start();//定时器开启
    
            //食物随机分布在界面
            foodx = 25 + 25 *random.nextInt(34);
            foody = 75 + 25 *random.nextInt(24);
    
    
    
        }
        public GamePanel(){
            init();
            //获得焦点和键盘事件
            this.setFocusable(true);//获得焦点事件
            this.addKeyListener(this);//获得键盘监听事件
        }
    
    
    
        @Override
        public void paint(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,16));
            g.drawString("长度" + length, 750, 35);
            g.drawString("分数" + score, 750, 50);
    
            //静态画法
    //        //把小蛇画上去
    //        Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头
    //        Data.body.paintIcon(this,g,snakeX[1],snakeY[1]);//第一个身体
    //        Data.body.paintIcon(this,g,snakeX[2],snakeY[2]);//第二个身体
    
            if(direction.equals("R")){
                Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头,需要判断方向
            }else if(direction.equals("L")){
                Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头,需要判断方向
            }else if(direction.equals("U")){
                Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头,需要判断方向
            }else if(direction.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]);//每一个身体
            }
    
            //画食物
            Data.food.paintIcon(this,g,foodx,foody);
    
            //游戏状态
            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) {
                direction = "U";
    
            }else if(keyCode == KeyEvent.VK_DOWN){
                direction = "D";
    
            }else if(keyCode == KeyEvent.VK_LEFT){
                direction = "L";
    
            }else if(keyCode == KeyEvent.VK_RIGHT){
                direction = "R";
    
            }
        }
    
        //事件监听,通过固定时间来判断
        @Override
        public void actionPerformed(ActionEvent e) {
            if(isStart && isFail ==false){//开始游戏则让小蛇动起来
                //吃食物
                if(foodx == snakeX[0] && foody == snakeY[0]){
                    length++;//长度加一
                    //分数加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(direction.equals("R")){
                    snakeX[0]=snakeX[0]+25;//蛇头
                    //如果超出范围
                    if(snakeX[0]>850){
                        snakeX[0]=25;
                    }
                }else if(direction.equals("L")){
                    snakeX[0]=snakeX[0]-25;//蛇头
                    //如果超出范围
                    if(snakeX[0]<25){
                        snakeX[0]=850;
                    }
                }else if(direction.equals("U")){
                    snakeY[0]=snakeY[0]-25;//蛇头
                    //如果超出范围
                    if(snakeY[0]<75){
                        snakeY[0]=650;
                    }
                }else if(direction.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 keyReleased(KeyEvent e) {
    
        }
    
        @Override
        public void keyTyped(KeyEvent e) {
    
        }
    
    
    }
    
    

    Data

    package com.chao.GUI.snakegame;
    
    import javax.swing.*;
    import java.net.URL;
    
    //数据中心
    public class Data {
        public static URL headerURL = Data.class.getResource("statics/header.png");
        public static ImageIcon header = new ImageIcon(headerURL);
    
        public static URL upURL = Data.class.getResource("statics/up.png");
        public static ImageIcon up = new ImageIcon(upURL);
        public static URL downURL = Data.class.getResource("statics/down.png");
        public static ImageIcon down = new ImageIcon(downURL);
        public static URL leftURL = Data.class.getResource("statics/left.png");
        public static ImageIcon left = new ImageIcon(leftURL);
        public static URL rightURL = Data.class.getResource("statics/right.png");
        public static ImageIcon right = new ImageIcon(rightURL);
    
        public static URL bodyURL = Data.class.getResource("statics/body.png");
        public static ImageIcon body = new ImageIcon(bodyURL);
    
        public static URL foodURL = Data.class.getResource("statics/food.png");
        public static ImageIcon food = new ImageIcon(foodURL);
    }
    
    

    优化方向:

    • 根据积分增加等级,改变速度

    • 撞墙游戏失败

    • 不能回头

    • 食物功能不同(有毒食物,高级食物)

    • 联机

    • 存档(数据库,io操作)

    ps:打jar包

    Project Structure->Artifacts->点+->ok

    Build->Build Artifacts->Build

    F:\IdeaJavaFile\GUI\out\artifacts\javaGUI_jar打开cmd

    命令

    java -jar javaGUI.jar
    
    展开全文
  • JAVA GUI编程

    2020-10-26 22:19:56
    GUI编程 因为java实验要用到这个,于是上b站粗略学了一下,感觉很多和前端都挺类似的,记录一下。 1.简介 Gui 的核心技术: Swing AWT 为什么要学习: 写出想要的小工具 维护swing界面 了解MVC架构,了解监听 2....

    GUI编程

    因为java实验要用到这个,于是上b站粗略学了一下,感觉很多和前端都挺类似的,记录一下。

    1.简介

    Gui 的核心技术: Swing AWT

    为什么要学习:

    1. 写出想要的小工具
    2. 维护swing界面
    3. 了解MVC架构,了解监听

    2.AWT

    2.1 AWT介绍

    1. 包含了很多类和接口
    2. 元素:窗口,按钮,文本框
    3. java.awt

    2.2 组件和容器

    1.Frame

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

    问题:发现窗口关闭不掉,停止java程序就行

    尝试回顾封装:

    package com.q.lesson1;
    
    import java.awt.*;
    
    /**
     * @author anonymity-0
     * @date 2020/10/18 - 20:02
     */
    public class TestFrame2 {
        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.blue);
            MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.red);
            MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.gray);
    
        }
    }
    class MyFrame extends Frame{
        static int id =0; //可能存在多个窗口,需要一个计数器
    
        public MyFrame(int x,int y,int w,int h,Color color){
            super("MyFrame"+(++id));
            setBounds(x,y,w,h);
            setVisible(true);
            setBackground(color);
        }
    }
    

    2. 面板

    解决关闭事件

    package main.java.com.q.lesson1;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    /**
     * @author anonymity-0
     * @date 2020/10/18 - 20:11
     * 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(1,1,1));
    
            //panel设置坐标,相对于frame
            panel.setBounds(50,50,400,400);
            panel.setBackground(new Color(253, 252, 252));
    
            //frame.add
            frame.add(panel);
            frame.setVisible(true);
    
            //监听事件,监听窗口关闭事件
    
            frame.addWindowListener(new WindowAdapter() {
                //窗口点击关闭时做的事情
                @Override
                public void windowClosing(WindowEvent e) {
                    //结束程序
                    System.exit(0);
                }
            });
        }
    }
    

    2.3.布局管理器

    • 流式布局

      package main.java.com.q.lesson1;
      
      import java.awt.*;
      import java.awt.event.WindowAdapter;
      import java.awt.event.WindowEvent;
      
      /**
       * @author anonymity-0
       * @date 2020/10/19 - 16:44
       */
      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(FlowLayout.LEFT));
              frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
              frame.setSize(200,200);
      
              //把按钮添加
              frame.add(button1);
              frame.add(button2);
              frame.add(button3);
              frame.setVisible(true);
      
              //关闭事件
              frame.addWindowListener(new WindowAdapter() {
                  @Override
                  public void windowClosing(WindowEvent e) {
                      System.exit(0);
                  }
              });
          }
      }
      
    • 东西南北中

      package main.java.com.q.lesson1;
      
      import java.awt.*;
      
      /**
       * @author anonymity-0
       * @date 2020/10/19 - 16:52
       */
      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(200,200);
              frame.setVisible(true);
          }
      }
      
    • 表格布局 Grid

      package main.java.com.q.lesson1;
      
      import java.awt.*;
      
      /**
       * @author anonymity-0
       * @date 2020/10/19 - 16:57
       */
      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();//自动布局
             // frame.setSize(200,200);
              frame.setVisible(true);
      
          }
      }
      

    总结:

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

    2.4.事件监听

    当某件事情发生的时候要干什么

    package main.java.com.q.lesson2;
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    /**
     * @author anonymity-0
     * @date 2020/10/20 - 8:00
     */
    public class TestActionEvent {
    
        public static void main(String[] args) {
            //按下按钮,触发一些事件
            Frame frame = new Frame("main.java.com.q.lesson2.TestActionEvent");
            Button button = new Button("button");
            //addActionListener需要一个ActionListener所以我们需要一个
            myActionListener myActionListener = new myActionListener();
            button.addActionListener(myActionListener);
    
            frame.add(button);
            frame.pack();
            windowClose(frame);//关闭窗口
            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("hello world!");
            }
        }
    
    package main.java.com.q.lesson2;
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    /**
     * @author anonymity-0
     * @date 2020/10/20 - 8:37
     */
    public class TestActionTwo {
        public static void main(String[] args) {
            //两个按钮实现同一个监听
            Frame frame = new Frame("开始-停止");
            Button btn1 = new Button("strat");
            Button btn2 = new Button("stop");
            btn2.setActionCommand("button2-stop");
            MyMonitor myMonitor = new MyMonitor();
            btn1.addActionListener(myMonitor);
            btn2.addActionListener(myMonitor);
    
            frame.add(btn1,BorderLayout.NORTH);
            frame.add(btn2,BorderLayout.SOUTH);
    
            frame.pack();
            frame.setVisible(true);
        }
    }
        class MyMonitor implements ActionListener{
    
            @Override
            public void actionPerformed(ActionEvent e) {
                //获得按钮的信息
                System.out.println("按钮被点击了:msg"+e.getActionCommand());
    
            }
    
    }
    

    2.5.输入框TextField 监听

    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    /**
     * @author anonymity-0
     * @date 2020/10/20 - 9:20
     */
    public class TestText01 {
        public static void main(String[] args) {
            new MyFrame();
        }
    }
    class MyFrame extends Frame{
        public MyFrame(){
            TextField textField = new TextField();
            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 textField = (TextField) e.getSource();//获得一些资源,返回了一个对象
            System.out.println(textField.getText());
            textField.setText("");
        }
    }
    

    2.6.简易计算器

    package main.java.com.q.lesson2;
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    /**
     * @author anonymity-0
     * @date 2020/10/20 - 9:35
     * 简易计算器
     */
    public class TestCalc {
        public static void main(String[] args) {
            Caculator caculator = new Caculator();
            caculator.loadFrame();
        }
    }
    
    //计算器类
    class  Caculator extends Frame{
        //属性
        TextField num1,num2,num3;
        public void loadFrame(){
            //3个文本框
            num1 = new TextField(10);//字符数
            num2 = new TextField(10);
            num3 = new TextField(20);
            //一个按钮
            Button button = new Button("=");
            //一个标签
            Label label = new Label("+");
            button.addActionListener(new MyCaculateListener(this));
            setLayout(new FlowLayout());
    
            //布局
            add(num1);
            add(label);
            add(num2);
            add(button);
            add(num3);
            setVisible(true);
            pack();
        }
        //监听器类
        private class MyCaculateListener implements ActionListener{
            //获取计算器,在一个类中组合另外一个类
            Caculator caculator =null;
    
            public MyCaculateListener(Caculator caculator) {
                this.caculator=caculator;
            }
    
            @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("");
            }
        }
    }
    

    组合+内部类回顾复习

    opp原则:组合大于继承

    //继承
    class A extends B{
    
    }
    //组合
    class A{
    	pubulic B b;
    }
    

    内部类

    更好的包装,内部类最大的好处,就是可以畅通无阻的访问外部类

    2.7画笔 Paint

    package main.java.com.q.lesson3;
    
    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.fillOval(100,100,100,100);//实心的圆
            g.setColor(Color.GREEN);
            g.fillRect(150,200,200,200);
    
            //养成习惯,画笔用完,将他还原到最初的颜色
            
        }
    

    2.8 鼠标监听

    目的:实现鼠标点击画画

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

    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.ArrayList;
    import java.util.Iterator;
    
    /**
     * @author anonymity-0
     * @date 2020/10/25 - 22:20
     */
    //鼠标监听事件
    public class TestMouseListener {
        public static void main(String[] args) {
             new MyFrame("画图");
        }
    }
    class  MyFrame extends Frame{
        ArrayList points;
        //画画需要画笔,需要监听当前的位置,需要集合来存储这个点
        public MyFrame(String title){
            super(title);
            setBounds(200,200,400,300);
            //存鼠标点击的点
            points = new ArrayList<>();
        //鼠标监听器,针对这个窗口
    
            setVisible(true);
            this.addMouseListener(new MyMouseListener());
        }
    
        @Override
        public void paint(Graphics g) {
            //画画,监听的鼠标的事件
            Iterator iterator = points.iterator();
            while (iterator.hasNext()){
                Point point = (Point) iterator.next();
                g.setColor(Color.CYAN);
                g.fillOval(point.x,point.y,10,10);
            }
        }
    
        //添加一个点到界面上
        public void  addPaint(Point point){
            points.add(point);
        }
        private class  MyMouseListener extends MouseAdapter{
            //鼠标按下
            @Override
            public void mousePressed(MouseEvent e) {
                MyFrame frame = (MyFrame) e.getSource();
                //点击的时候就会在界面上产生一个点
                //这个点就是鼠标的点
                frame.addPaint(new Point(e.getX(),e.getY()));
                //每次点击鼠标都要重新画一遍
                frame.repaint();
            }
        }
    }
    

    2.9 窗口监听

    package main.java.com.q.lesson3;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    /**
     * @author anonymity-0
     * @date 2020/10/25 - 22:55
     */
    public class TestWindow {
        public static void main(String[] args) {
            new WindowFrame();
        }
    }
    class WindowFrame extends Frame{
        public WindowFrame(){
            setBackground(Color.white);
            setBounds(100,100,200,200);
            setVisible(true);
            this.addWindowListener(new WindowAdapter() {
                //匿名内部类
                @Override
                //关闭窗口
                public void windowClosing(WindowEvent e) {
                    System.out.println("你点击了关闭");
                    System.exit(0);
                }
    
                @Override
                public void windowOpened(WindowEvent e) {
                    System.out.println("windowOpened");
                }
    
                @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");
                }
            });
        }
    }
    

    2.10 键盘监听

    package main.java.com.q.lesson3;
    
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    /**
     * @author anonymity-0
     * @date 2020/10/25 - 22:55
     */
    public class TestWindow {
        public static void main(String[] args) {
            new WindowFrame();
        }
    }
    class WindowFrame extends Frame{
        public WindowFrame(){
            setBackground(Color.white);
            setBounds(100,100,200,200);
            setVisible(true);
            this.addWindowListener(new WindowAdapter() {
                //匿名内部类
                @Override
                //关闭窗口
                public void windowClosing(WindowEvent e) {
                    System.out.println("你点击了关闭");
                    System.exit(0);
                }
    
                @Override
                public void windowOpened(WindowEvent e) {
                    System.out.println("windowOpened");
                }
    
                @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");
                }
            });
        }
    }
    

    3.Swing

    3.1窗口、面板

    package main.java.com.q.lesson4;
    
    import javax.swing.*;
    import java.awt.*;
    
    /**
     * @author anonymity-0
     * @date 2020/10/25 - 23:32
     */
    public class JFrameDemo {
        //init();初始化
        public void init(){
            //顶级窗口
            JFrame jf = new JFrame("这是一个Jframe窗口");
            jf.setBounds(100,100,200,200);
            jf.setVisible(true);
            jf.setBackground(Color.cyan);   //  无效
    
            //设置文字 Jlable
            JLabel label = new JLabel("haha");
            jf.add(label);
            
            //让文本标签居中
            label.setHorizontalAlignment(SwingConstants.CENTER);
    
            //容器实例化 获得容器
            Container contentPane = jf.getContentPane();
            contentPane.setBackground(Color.CYAN);
            //关闭事件
            jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
        public static void main(String[] args) {
            //建立一个窗口
            new JFrameDemo().init();
        }
    }
    

    3.2 弹窗

    package main.java.com.q.lesson4;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    /**
     * @author anonymity-0
     * @date 2020/10/25 - 23:45
     */
    //主窗口
    public class DialogDemo extends JFrame {
        public DialogDemo(){
            this.setVisible(true);
            this.setSize(700,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
            //JFrame 放东西,容器
            Container container = this.getContentPane();
            //绝对布局
            container.setLayout(null);
            //按钮
            JButton button = new JButton("点我");//创建
            button.setBounds(30,30,200,50);
    
            //点击按钮的时候弹出弹窗
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    //弹窗
                    new MyDialogDemo();
                }
            });
            container.add(button);
        }
    
        public static void main(String[] args) {
            new DialogDemo();
        }
    }
    //弹窗的窗口
    class MyDialogDemo extends JDialog{
    
    
        public MyDialogDemo() {
            this.setVisible(true);
            this.setBounds(100,100,500,500);
            Container container = this.getContentPane();
            container.setLayout(null);
            container.add(new JLabel("今天不学习,明天变垃圾"));
    
        }
    }
    

    3.3 标签

    label

    new JLabel("xxx");
    

    图标 ICON

    package main.java.com.q.lesson4;
    
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    
    /**
     * @author anonymity-0
     * @date 2020/10/26 - 16:47
     */
    public class ImageIconDemo extends JFrame {
        public ImageIconDemo(){
            //获取图片的地址,根据类获得路径的地址
            JLabel label = new JLabel("ImageIconDemo");
            URL url = ImageIconDemo.class.getResource("test.jpeg");
            ImageIcon imageIcon = new ImageIcon();
            label.setIcon(imageIcon);
            label.setHorizontalAlignment(SwingConstants.CENTER);
            Container container = getContentPane();
            container.add(label);
            setVisible(true);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
        }
        public static void main(String[] args) {
            new ImageIconDemo();
        }
    }
    

    3.4 面板

    JPaner

    package main.java.com.q.lesson5;
    
    import javax.swing.*;
    import java.awt.*;
    
    /**
     * @author anonymity-0
     * @date 2020/10/26 - 16:58
     */
    public class JPanelDemo extends JFrame {
        public JPanelDemo() {
            Container container = this.getContentPane();
            container.setLayout(new GridLayout(2,1,10,10));//后面参数的意思
    
            JPanel panel1 = new JPanel(new GridLayout(1, 3));
    
            panel1.add(new JButton("1"));
            panel1.add(new JButton("2"));
            panel1.add(new JButton("3"));
            container.add(panel1);
            this.setVisible(true);
            this.setSize(500,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new JPanelDemo();
        }
    }
    
    

    带滚动条的面板

    JScrollPannel

    package main.java.com.q.lesson5;
    
    import javax.swing.*;
    import java.awt.*;
    
    /**
     * @author anonymity-0
     * @date 2020/10/26 - 17:05
     */
    public class JscrollDemo extends JFrame {
        public static void main(String[] args) {
            new JscrollDemo();
        }
    
        public JscrollDemo() {
            Container container = this.getContentPane();
    //文本框
            JTextArea textArea = new JTextArea(20, 50);
            textArea.setText("hahaha");
            container.add(textArea);
            //scroll面板
            JScrollPane scrollPane = new JScrollPane(textArea);
            container.add(scrollPane);
            this.setVisible(true);
            this.setBounds(100,100,300,350);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    }
    

    3.5 按钮

    • 图片按钮

      package main.java.com.q.lesson5;
      
      import javax.swing.*;
      import java.awt.*;
      import java.net.URL;
      
      /**
       * @author anonymity-0
       * @date 2020/10/26 - 17:46
       */
      public class ButtonDemo01 extends JFrame {
          public ButtonDemo01() {
              Container container = this.getContentPane();
              //将图片变成图标
              URL url = ButtonDemo01.class.getResource("test.jpeg");
              Icon icon = new ImageIcon(url);
              //把这个图标放在按钮上
              JButton button = new JButton();
              button.setIcon(icon);
              button.setToolTipText("图片按钮");
      
              container.add(button);
              this.setSize(500,300);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new ButtonDemo01();
          }
      
      }
      
    • 单选按钮

      package main.java.com.q.lesson5;
      
      import javax.swing.*;
      import java.awt.*;
      import java.net.URL;
      
      /**
       * @author anonymity-0
       * @date 2020/10/26 - 17:56
       */
      public class JButtonDemo02 extends JFrame{
          public JButtonDemo02() {
              Container container = this.getContentPane();
              //将图片变成图标
              URL url = ButtonDemo01.class.getResource("test.jpeg");
              Icon icon = new ImageIcon(url);
              //单选框
              JRadioButton radioButton01 = new JRadioButton("JRadioButton01");
              JRadioButton radioButton02 = new JRadioButton("JRadioButton02");
              JRadioButton radioButton03 = new JRadioButton("JRadioButton03");
      
              //由于单选框只能选择一个,所以要分组
              ButtonGroup buttonGroup = new ButtonGroup();
              buttonGroup.add(radioButton01);
              buttonGroup.add(radioButton02);
              buttonGroup.add(radioButton03);
      
              container.add(radioButton01,BorderLayout.CENTER);
              container.add(radioButton02,BorderLayout.NORTH);
              container.add(radioButton03,BorderLayout.SOUTH);
              this.setSize(500,300);
              this.setVisible(true);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new JButtonDemo02();
          }
      }
      
    • 复选按钮

    package main.java.com.q.lesson5;
    
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    
    /**
     * @author anonymity-0
     * @date 2020/10/26 - 20:44
     */
    public class JButtonDemo03 extends JFrame{
        public JButtonDemo03() {
            Container container = this.getContentPane();
            //将图片变成图标
            URL url = ButtonDemo01.class.getResource("test.jpeg");
            Icon icon = new ImageIcon(url);
    
            JCheckBox checkBox01 = new JCheckBox("checkBox01");
            JCheckBox checkBox02 = new JCheckBox("checkBox02");
    
            container.add(checkBox01,BorderLayout.NORTH);
            container.add(checkBox02,BorderLayout.SOUTH);
            this.setSize(500,300);
            this.setVisible(true);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new JButtonDemo03();
        }
    }
    

    3.6 列表

    • 下拉框

      package main.java.com.q.lesson6;
      
      import javax.swing.*;
      import java.awt.*;
      
      /**
       * @author anonymity-0
       * @date 2020/10/26 - 20:51
       */
      public class TestComboboxDemo01 extends JFrame {
          public TestComboboxDemo01(){
              Container container = getContentPane();
      
              JComboBox comboBox = new JComboBox();
      
              comboBox.addItem(null);
              comboBox.addItem("学习中");
              comboBox.addItem("游戏中");
              comboBox.addItem("睡觉中");
      
              container.add(comboBox);
              this.setVisible(true);
              this.setSize(500,350);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
          new TestComboboxDemo01();
          }
      }
      
    • 列表框

      package main.java.com.q.lesson6;
      
      import javax.swing.*;
      import java.awt.*;
      
      /**
       * @author anonymity-0
       * @date 2020/10/26 - 20:55
       */
      public class TestComboboxDemo02  extends JFrame {
          public TestComboboxDemo02() {
              Container container = getContentPane();
      
              //生成列表内容
              String[] contents ={"1","2","3"};
              //列表中放入内容
              JList list = new JList(contents);
              
              container.add(list);
              this.setVisible(true);
              this.setSize(500,350);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      
          public static void main(String[] args) {
              new TestComboboxDemo02();
          }
      }
      
    • 应用场景

      • 选择地区
      • 展示信息

    3.7 文本框

    • 文本框
    import javax.swing.*;
    import java.awt.*;
    
    /**
     * @author anonymity-0
     * @date 2020/10/26 - 21:01
     */
    public class TestTextDemo01 extends JFrame {
        public static void main(String[] args) {
            new TestTextDemo01();
        }
    
        public TestTextDemo01() {
            Container container = this.getContentPane();
    
            JTextField textField = new JTextField("Hello");
            JTextField textField2 = new JTextField("world!");
    
            container.add(textField,BorderLayout.SOUTH);
            container.add(textField2,BorderLayout.NORTH);
            this.setVisible(true);
            this.setSize(300,500);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    }
    
    • 密码框

      package main.java.com.q.lesson6;
      
      import javax.swing.*;
      import java.awt.*;
      
      /**
       * @author anonymity-0
       * @date 2020/10/26 - 21:59
       */
      public class TestTextDemo02 extends JFrame {
          public static void main(String[] args) {
              new TestTextDemo02();
          }
      
          public TestTextDemo02() {
              Container container = this.getContentPane();
      
              JPasswordField passwordField = new JPasswordField();
              passwordField.setEchoChar('/');
              container.add(passwordField);
              this.setVisible(true);
              this.setSize(300,500);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      }
      
    • 文本域

      package main.java.com.q.lesson5;
      
      import javax.swing.*;
      import java.awt.*;
      
      /**
       * @author anonymity-0
       * @date 2020/10/26 - 17:05
       */
      public class JscrollDemo extends JFrame {
          public static void main(String[] args) {
              new JscrollDemo();
          }
      
          public JscrollDemo() {
              Container container = this.getContentPane();
      //文本框
              JTextArea textArea = new JTextArea(20, 50);
              textArea.setText("hahaha");
              container.add(textArea);
              //scroll面板
              JScrollPane scrollPane = new JScrollPane(textArea);
              container.add(scrollPane);
              this.setVisible(true);
              this.setBounds(100,100,300,350);
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          }
      }
      

    {
    Container container = this.getContentPane();

          JPasswordField passwordField = new JPasswordField();
          passwordField.setEchoChar('/');
          container.add(passwordField);
          this.setVisible(true);
          this.setSize(300,500);
          this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      }
    

    }

    
    - 文本域
    
    ```java
    package main.java.com.q.lesson5;
    
    import javax.swing.*;
    import java.awt.*;
    
    /**
     * @author anonymity-0
     * @date 2020/10/26 - 17:05
     */
    public class JscrollDemo extends JFrame {
        public static void main(String[] args) {
            new JscrollDemo();
        }
    
        public JscrollDemo() {
            Container container = this.getContentPane();
    //文本框
            JTextArea textArea = new JTextArea(20, 50);
            textArea.setText("hahaha");
            container.add(textArea);
            //scroll面板
            JScrollPane scrollPane = new JScrollPane(textArea);
            container.add(scrollPane);
            this.setVisible(true);
            this.setBounds(100,100,300,350);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    }
    
    展开全文

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,851
精华内容 1,540
关键字:

javagui编程

java 订阅