玩命加载中 . . .

GUI(53)


GUI

简介:

  1. GUI:图形用户编程。
  2. GUI核心技术:Swing/AWT。
  3. 缺点:
     界面不美观且需要jre环境。
    
  4. 为什么学GUI?
    • 可以自己实现一些小工具。
    • 工作时候可能会维护到Swing界面,概率极小。
    • 了解MVC架构,了解监听事件。

AWT

GUI继承结构图

概述:

Java使用AWT和Swing类完成图形用户界面编程,AWT的全称是抽象窗口工具集,它是Sun最早提供的GUI库,提供了一些基本的功能,但功能比较有限,所以后来又提供了Swing库,Swing库替代了绝大部分的AWT组件,但需要使用AWT的事件处理机制通过使用AWT和Swing提供的图形界面组件库,Java的图形界面编程可以变得比较简单,程序只要依次创建所需的图形组件,并以合适的方式将这些组件组织在一起,就可以开发出不错的用户界面。

容器

任何窗口都可被分解成一个空的容器,容器里盛装了大量的基本组件,通过设置这些基本组件的大小,位置等属性,就可以将该空的容器和基本的组件组成一个整体的窗口。

AWT提供了两种主要的容器类型:

Frame(窗口)

Frame:它是一个容器,允许程序员把其他组件添加到它里面,把它们组织起来,并把它们呈现给用户。

    public static void main(String[] args) {
        // 创建一个Frame对象
        Frame frame = new Frame();
        // 设置可见性
        frame.setVisible(true);
        // 设置窗口大小
        frame.setSize(200,200);
        // 设置背景颜色
        frame.setBackground(Color.CYAN);
        // 弹出的初始位置
        frame.setLocation(200,200);
        // 设置固定大小
        frame.setResizable(false);
        // 自适应大小
        frame.pack();
    }

Panel(面板)

Panel:可作为容器容纳其他组件,但不能独立存在,必须被添加到其它的容器中。

    public static void main(String[] args) {
        // 创建界面
        Frame frame = new Frame();
        // 设置界面的坐标/宽高
        frame.setBounds(200,200,500,500);
        // 设置界面背景色
        frame.setBackground(Color.CYAN);
        // 设置可见度
        frame.setVisible(true);
        // 设置界面布局
        frame.setLayout(null);

        // 创建Panel面板对象
        Panel panel = new Panel();
        // 设置panel面板的坐标/宽高(相对于界面的坐标)
        panel.setBounds(20,20,300,300);
        // 设置panel面板的背景颜色
        panel.setBackground(Color.BLUE);

        // 在frame界面中添加panel面板
        // 由于这种模式需要重写很多方法所以可以使用适配器模式来绑定关闭事件
        // 添加关闭close事件
        // 监听事件,监听窗口关闭事件 System.exit(0);
        // 以下方法是使用适配器模式来绑定关闭事件的
        frame.addWindowListener(new WindowAdapter() {
            // 窗口点击关闭时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                // 结束程序
                System.exit(0);
            }
        });
    }

Window:可独立存在的顶级窗口。

组件

TextField(文本框)

public class FreameTest03 {
    public static void main(String[] args) {
        new MyActIonLl03();
    }
}
class MyActIonLl03 extends Frame {
    public MyActIonLl03() {
        // 窗口可见度
        setVisible(true);
        // 窗口大小
        setBounds(200,200,300,80);
        // 窗口颜色
        setBackground(Color.CYAN);
        // 布局
        setLayout(new GridLayout());    // 流式布局

        // 关闭窗口事件
        windowClose(this);

        // 创建一个文本框
        TextField text = new TextField();
        // 设置文本框中的字体
        text.setFont(new Font("宋体", 10,30));
        // 设置用户输入内容替换为*号
        text.setEchoChar('*');
        // 将文本框添加到窗口中
        add(text);
        
        // 让窗口内的组件自适应大小(注:需要在组件添加到窗口后最后加自适应大小)
        // pack();

        // 监听文本框事件
        text.addActionListener(new MyActIonLl04());
    }
    // 关闭窗口事件
    private static void windowClose(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
// 文本监听事件
class MyActIonLl04 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // 返回事件源对象(需要转型)
        TextField textField = (TextField)e.getSource();
        // 打印文本框的值
        System.out.println(textField.getText());
        // 每次一回车就清空文本框中的值
        textField.setText("");
    }
}

Paint(画笔)

public class FreameTest07 {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}
class MyPaint extends Frame {
    public void loadFrame() {
        // 创建窗口
        setBackground(Color.WHITE);
        setLayout(new FlowLayout());
        setBounds(200,200,500,500);
        setVisible(true);
        windowClosing(this);
    }
    // 画笔
    @Override
    public void paint(Graphics g) {
        g.setColor(Color.GREEN); // 设置圆的颜色
        g.drawOval(50,50,50,50);    // 空心圆
        g.fillOval(100,100,100,100);    // 实心圆
        g.drawRect(200,200,100,100);    // 空矩形
        // 注:画笔颜色用完还原为最初的颜色
    }
    public void windowClosing(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

Label(标签)

class MyFrame extends Frame {
    public MyFrame() throws HeadlessException {
        // 设置背景颜色
        setBackground(Color.CYAN);
        // 可见性
        setVisible(true);
        // 坐标/尺寸
        setBounds(200,200,200,200);
        // 布局
        setLayout(new FlowLayout());
        // 关闭
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        // 创建标签
        Label label = new Label("abc");
        // 添加到窗口
        this.add(label);
    }
}

布局管理器

Java提供了布局管理器来组件在容器中的布局,而不是直接设置组件位置和大小。

常见的有:

FlowLayout(流式布局)

FlowLayout:组件向某个方向排列,遇到边界就折回,从头开始排列。

    public static void main(String[] args) {
        // 流式布局

        // 创建窗口
        Frame frame = new Frame();
        // 设置大小
        frame.setBounds(200,200,300,300);
        // 设置可见度
        frame.setVisible(true);
        // 设置颜色
        frame.setBackground(Color.CYAN);
        // 设置流式布局
        frame.setLayout(new FlowLayout());

        // 创建组件
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");

        // 窗口添加组件
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
    }

BorderLayout(东西南北中布局)

BorderLayout:将容器分为东,西,南,北,中五个区域普通组件被放置在这五个区域的任意一个中。注:这个布局不需要设置布局,只需添加组件时设置相应位置即可。

    public static void main(String[] args) {
        // 东南西北中布局

        // 创建窗口
        Frame frame = new Frame();
        // 设置大小
        frame.setBounds(200,200,300,300);
        // 设置可见度
        frame.setVisible(true);
        // 设置颜色
        frame.setBackground(Color.CYAN);
        // 设置流式布局
        // frame.setLayout(new BroderLayout());

        // 创建组件
        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);
    }

GridLayout(表格布局)

GridLayout:将容器分割成纵横线分隔的网格,每个网格所占的区域大小相同。

    public static void main(String[] args) {
        // 表格布局

        // 创建窗口
        Frame frame = new Frame();
        // 设置大小
        frame.setBounds(200,200,300,300);
        // 设置可见度
        frame.setVisible(true);
        // 设置颜色
        frame.setBackground(Color.CYAN);
        // 设置表格布局(3行2列布局)
        frame.setLayout(new GridLayout(3,2));

        // 创建组件
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");
        Button button6 = new Button("button6");

        // 窗口添加组件
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);
    }

布局小结:AWT的布局管理与前端布局类似,唯一区别就是,面板叠面板,但是根据界面样式,通过合理规划使用相应的布局管理嵌套做出来。

事件处理

概述:

Frame和组件本身没有事件处理的能力,必须由特定对象(事件监听器)来处理。
实现事件处理机制的步骤:

  1. 实现事件监听类,必须实现XxxListener接口。
  2. 创建普通组件(事件源),创建事件监听对象。
  3. 调用addXxxListener()方法,将事件监听器注册给普通组件,当事件源上发生指定的事件时,AWT会触发事件监听器,由事件监听器调用相应的方法(事件处理器)来处理事件,事件源上发生的事件会作为参数传入事件处理器。

鼠标监听

// 鼠标监听
public class FreameTest08 {
    public static void main(String[] args) {
        new MyPaint02("画画");
    }
}
class MyPaint02 extends Frame {
    private  ArrayList mouseXY;
    // 画画需要监听鼠标当前的实时位置
    public MyPaint02(String title) {
        super(title);
        setBounds(200,200,400,400);
        setBackground(Color.yellow);
        setLayout(null);
        setVisible(true);
        windowClosing(this);
        // 鼠标监听,针对的是这个窗口的鼠标
        addMouseListener(new MyMouseAdapter()); // 鼠标监听器
        // 读取鼠标中按下的点
        mouseXY = new ArrayList<>();
    }

    // 创建画笔
    @Override
    public void paint(Graphics g) {
        // 画画,需要监听鼠标事件
        g.setColor(Color.red);
        Iterator integer = mouseXY.iterator();
        while (integer.hasNext()) {
            // 将迭代器中的对象转换成Point对象
            Point point = (Point)integer.next();
            // 将获取到的值通过画笔画出来
            g.fillOval(point.x,point.y,20,20);
        }
    }

    // 将鼠标按下的x/y坐标存储到集合
    public void getMouseXY(Point point) {
        mouseXY.add(point);
    }

    // 鼠标事件成员内部类
    // 鼠标抽象适配器类
    private class MyMouseAdapter extends MouseAdapter {
        // 重写鼠标按下事件
        @Override
        public void mousePressed(MouseEvent e) {
            // 获取事件源对象
            MyPaint02 frame = (MyPaint02)e.getSource();
            // 获取鼠标源对象的x y坐标
            getMouseXY(new Point(e.getX(),e.getY()));
            // 注:Point对象参数要的是鼠标按下的对象不是frame对象
            System.out.println("x:" + new Point(e.getX(),e.getY()).getX() + "y:" + new Point(e.getX(),e.getY()).getY());
            // 每次点击鼠标都要重画一次
            frame.repaint();
        }
    }
    // 关闭窗口
    public void windowClosing(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

窗口监听

public class FreameTest09 {
    public static void main(String[] args) {
        new MyWindow("窗口事件");
    }
}
class MyWindow extends Frame {
    public MyWindow(String title) throws HeadlessException {
        super(title);
        setBounds(200,200,300,300);
        setBackground(Color.yellow);
        setVisible(true);
        // 第一种绑定窗口事件方法
        // addWindowListener(new MyWindowListener());
        // 推荐使用第二种绑定窗口事件方法:匿名内部类
        this.addWindowListener(new WindowAdapter() {
            // 以下只模拟窗口几种窗口事件
            // 当窗口激活触发事件
            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("当前窗口已激活");
            }
            // 当窗口关闭时触发事件
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("当前窗口已关闭");
                // System.exit(0);
            }
        });
    }

    // 第一种绑定窗口事件方法:成员内部类
    // 抽象类适配器
/*    private class MyWindowListener extends WindowAdapter {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }*/
}

键盘监听

// 鼠标事件
public class FreameTest10 {
    public static void main(String[] args) {
        new KeyBoard();
    }
}
class KeyBoard extends Frame {
    public KeyBoard() throws HeadlessException {
        setVisible(true);
        setBounds(200,200,400,400);
        setBackground(Color.CYAN);
        windowClosing(this);
        this.addKeyListener(new KeyAdapter() {
            // 鼠标按下事件
            @Override
            public void keyPressed(KeyEvent e) {
                // 获取键盘上相应的码
                int keyboard = e.getKeyCode();  // 当前用户按下的码
                if (keyboard == KeyEvent.VK_UP) {
                    System.out.println("您按下了上键");
                }
            }
        });
    }
    public void windowClosing(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

练习:简易计算器

面向过程:实现简易计算器计算
// 实现两个按钮监听共同一个事件
public class FreameTest02 {
    public static void main(String[] args) {
        Frame frame = new Frame("练习");
        // 坐标/窗口大小
        frame.setBounds(200,200,300,300);
        // 颜色
        frame.setBackground(Color.blue);
        // 布局
        frame.setLayout(new BorderLayout());
        // 可见
        frame.setVisible(true);
        // 关闭
        windowClosing02(frame);

        // 事件绑定处理
        Button btn1 = new Button("btn1");
        Button btn2 = new Button("btn2");
        // 添加到窗口
        frame.add(btn1,BorderLayout.NORTH);
        frame.add(btn2,BorderLayout.SOUTH);
        // 事件绑定
        btn1.addActionListener(new MyActIonLl02());
        btn2.addActionListener(new MyActIonLl02());
        // 设置按钮的标识
        // 按钮标识相当于html中的id与class具有一定的唯一性
        btn1.setActionCommand("btn1");
        btn2.setActionCommand("btn2");
    }
    public static void windowClosing02(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
// 新建一个button事件的实现类
class MyActIonLl02 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String btn1 = e.getActionCommand();
        String btn2 = e.getActionCommand();
        if (btn1.equals("btn1")) {
            System.out.println("btn1被点击了");
        }else if(btn1.equals("btn2")) {
            System.out.println("btn2被点击了");
        }
    }
}
优化为:面向对象程序思想
// 优化为面向对象思路
public class FreameTest05 {
    public static void main(String[] args) {
        // 创建计算器对象
        new Calculator01().loadFrame();
    }
}

// 计算器
class Calculator01 extends Frame {
    // 属性
    TextField textField1,textField2,textField3;
    // 方法
    public void loadFrame() {
        // 设置窗口可见性
        setVisible(true);
        // 设置流式布局
        setLayout(new FlowLayout());
        // 设置窗口关闭
        windowClosing(this);

        // 创建三个文本框
        textField1 = new TextField(10);
        textField2 = new TextField(10);
        textField3 = new TextField(20);
        // 创建标签(类似于前端的p标签专门添加文字的)
        Label label = new Label("+");
        // 创建按钮
        Button button = new Button("=");
        // 给按钮创建监听事件
        button.addActionListener(new MyActIonLl06(this));

        // 组件添加到窗口
        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);

        // 窗口自适应大小(注:需要在组件添加到窗口后最后加自适应大小)
        pack();
    }
    private static void windowClosing(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

// 监听器
class MyActIonLl06 implements ActionListener {
    // 获取当前监听对象(使用OOP组合设计模式)
    Calculator01 calculator01 = null;
    public MyActIonLl06(Calculator01 calculator01) {
        // 获取当前计算器的对象
        this.calculator01 = calculator01;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // 将计算结果返回给第三个文本框
        int i1 = Integer.parseInt(calculator01.textField1.getText());
        int i2 = Integer.parseInt(calculator01.textField2.getText());
        calculator01.textField3.setText(i1+i2+"");
        // 将文本框值清空
        calculator01.textField1.setText("");
        calculator01.textField2.setText("");
    }
}
优化为:内部类
// 在面向对象基础上在进行优化
public class FreameTest06 {
    public static void main(String[] args) {
        // 创建计算器对象
        new Calculator01().loadFrame();
    }
}

// 计算器
class Calculator02 extends Frame {
    // 属性
    TextField textField1,textField2,textField3;
    // 方法
    public void loadFrame() {
        // 设置窗口可见性
        setVisible(true);
        // 设置流式布局
        setLayout(new FlowLayout());
        // 设置窗口关闭
        windowClosing(this);

        // 创建三个文本框
        textField1 = new TextField(10);
        textField2 = new TextField(10);
        textField3 = new TextField(20);
        // 创建标签(类似于前端的p标签专门添加文字的)
        Label label = new Label("+");
        // 创建按钮
        Button button = new Button("=");
        // 给按钮创建监听事件
        button.addActionListener(new MyActIonLl07());

        // 组件添加到窗口
        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);

        // 窗口自适应大小(注:需要在组件添加到窗口后最后加自适应大小)
        pack();
    }
    private static void windowClosing(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    // 监听器
    // 内部类最大的优点就是畅通无阻访问外部类的属性和方法
    private class MyActIonLl07 implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 将计算结果返回给第三个文本框
            int i1 = Integer.parseInt(textField1.getText());
            int i2 = Integer.parseInt(textField2.getText());
            textField3.setText(i1+i2+"");
            // 将文本框值清空
            textField1.setText("");
            textField2.setText("");
        }
    }
}

Swing

概述:

​ 为了解决AWT组件的缺陷,特别是跨平台的问题,在JDK1.2版本后提供了新的Swing包,javax.swing提供,Swing是在AWT的基础上构建的一套新的图形界面组件,所有组建均是由java书写,具有良好的跨平台性,由于Swing没有使用本地方法实现图形功能,因此提出把Swing组件称之为轻量级组件。
注意:Swing组建是在AWT基础上建立的,而不是替代AWT的,AWT是根基,Swing是发展。

容器

任何窗口都可被分解成一个空的容器,容器里盛装了大量的基本组件,通过设置这些基本组件的大小,位置等属性,就可以将该空的容器和基本的组件组成一个整体的窗口。

Swing提供了两种主要的容器类型:

JFrame(窗口)

  1. JFrame和Frame的区别:

    1. JFrame与Frame关闭窗口的方式不同:

      • DO_NOTHING_ON_CLOSE(在 WindowConstants 中定义):不执行任何操作;要求程序在已注册的WindowListener 对象的 windowClosing 方法中处理该操作。
      • HIDE_ON_CLOSE(在 WindowConstants 中定义):调用任意已注册的 WindowListener 对象后自动隐藏该窗体。
      • DISPOSE_ON_CLOSE(在 WindowConstants 中定义):调用任意已注册 WindowListener 的对象后自动隐藏并释放该窗体。
      • EXIT_ON_CLOSE(在 JFrame 中定义):使用 System exit 方法退出应用程序。仅在应用程序中使用。
    2. Frame设置颜色与JFrame不同:

      • Frame:直接设置颜色。

        setBackground(Color.);
        
      • JFrame:需要先获取当前窗口对象才可以设置颜色。

                Container container = this.getContentPane();    // 获取窗口对象
                container.setBackground(Color.BLUE);            // 设置颜色
        
  2. JFrame创建方式:

    class MyJFrame extends JFrame {
        public MyJFrame() throws HeadlessException {
            // 设置JFrame窗口可见性
            setVisible(true);
            // 设置JFrame坐标/宽高
            setBounds(200,200,300,300);
            // JFrame为顶级窗口,所以不可以直接设置背景颜色,需要获取此窗口的对象才能设置
            Container container = this.getContentPane();    // 获取窗口对象
            container.setBackground(Color.BLUE);            // 设置窗口颜色
            // 设置固定大小
            setResizable(false);
            // 设置JFrame的关闭事件
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    }
    

JPanel(面板)

JPanel:可作为容器容纳其他组件,但不能独立存在,必须被添加到其它的容器中。

class MyJPanel extends JFrame {
    public MyJPanel(String title) {
        super(title);
        // 窗口可见
        setVisible(true);
        // 坐标/大小
        setBounds(200,200,300,300);
        // 获取窗口对象
        Container container = this.getContentPane();
        // 设置颜色
        container.setBackground(Color.CYAN);
        // 东南西北布局
        setLayout(new BorderLayout());

        // 创建panel1面板
        JPanel jPanel1 = new JPanel();
        // 颜色
        jPanel1.setBackground(Color.PINK);
        // 添加到窗口布局的北边
        add(jPanel1,BorderLayout.NORTH);

        // 创建panel2面板
        JPanel jPanel2 = new JPanel();
        // 颜色
        jPanel2.setBackground(Color.BLUE);
        // 添加到窗口布局的北边
        add(jPanel2,BorderLayout.SOUTH);

        // 创建panel3面板
        JPanel jPanel3 = new JPanel();
        // 颜色
        jPanel3.setBackground(Color.GREEN);
        // 添加到窗口布局的北边
        add(jPanel3,BorderLayout.CENTER);

        // 创建panel4面板
        JPanel jPanel4 = new JPanel();
        // 颜色
        jPanel4.setBackground(Color.GRAY);
        // 添加到窗口布局的北边
        add(jPanel4,BorderLayout.WEST);

        // 创建panel4面板
        JPanel jPanel5 = new JPanel();
        // 颜色
        jPanel5.setBackground(Color.MAGENTA);
        // 添加到窗口布局的北边
        add(jPanel5,BorderLayout.EAST);
    }
}

JDialog(弹窗)

class MyJFrame02 extends JFrame {
    public MyJFrame02(String title) throws HeadlessException {
        super(title);
        // 坐标/尺寸
        setBounds(200,200,300,100);
        // 可见性
        setVisible(true);
        // 窗口关闭
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        // 获取窗口对象
        Container jFrame = this.getContentPane();
        // 设置颜色
        jFrame.setBackground(Color.CYAN);
        // 绝对布局
        jFrame.setLayout(new BorderLayout());

        // 创建按钮
        JButton btn = new JButton("点我弹出弹窗");
        // 设置按钮尺寸
        btn.setBounds(0,0,300,100);
        // 按钮添加事件
        btn.addActionListener(new ActionListener() {    // 监听器
            @Override
            public void actionPerformed(ActionEvent e) {    // 点击按钮事件
                // 弹窗
                new MyJDialog01();
                System.out.println("sss");
            }
        });
        // 添加按钮
        jFrame.add(btn,BorderLayout.CENTER);
    }
}
class MyJDialog01 extends JDialog {
    public MyJDialog01() {
        // 弹窗可见性
        setVisible(true);
        // 坐标/尺寸
        setBounds(200,200,500,500);
        // 返回此对话框的contentPane对象。
        Container container = this.getContentPane();
        // 颜色
        container.setBackground(Color.CYAN);

        // 添加标签
        JLabel jLabel = new JLabel("这是一个弹窗");
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);   // 设置标签中的文字居中
        // 添加到弹窗中
        container.add(jLabel);
    }
}

JScrollPane(滚动面板)

class MyFrame05 extends JFrame {
    public MyFrame05(String title) throws HeadlessException {
        super(title);
        setBounds(200,200,800,400);
    
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new GridLayout(2,1,50,50));
        Container container = this.getContentPane();
        container.setBackground(Color.GREEN);

        // 创建一个文本域
        TextArea textArea = new TextArea(20,20);
        // 创建一个可滚动视图面板
        JScrollPane pane = new JScrollPane(textArea);
        add(pane);

        // 添加btn按钮
        JButton btn = new JButton("按钮");
        // 添加到面板
        add(btn);
           setVisible(true);
    }
}

组件

JLabel(标签)

class MyJFrame03 extends JFrame {
    public MyJFrame03(String title) throws HeadlessException {
        super(title);
        setBounds(200,200,300,300);
        setLayout(new FlowLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container container = this.getContentPane();
        container.setBackground(Color.CYAN);
        // 创建JLabel标签
        JLabel jLabel = new JLabel("这是一个JLabel标签");
        // 居中文字
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        // 添加到窗口中
        container.add(jLabel);
        
        // 设置窗口可见度
        setVisible(true);
    }
}

ICO(图片)

class MyFrame04 extends JFrame {
    public MyFrame04(String title) throws HeadlessException {
        super(title);
        setBounds(200,200,300,300);
        setLayout(new FlowLayout());
        Container container = getContentPane();
        container.setBackground(Color.CYAN);

        // 创建ICO图片
        JLabel jLabel = new JLabel("ico图像");
        // 从本类中获取相应的资源文件
        URL url = MyFrame04.class.getResource("ico5.jpg");
        // 创建imageIcon并将url传进去
        ImageIcon imageIcon = new ImageIcon(url);
        // jLabel设置图片
        jLabel.setIcon(imageIcon);
        // 居中
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        // 添加到窗口
        container.add(jLabel);
        
        // 设置窗口可见度
        setVisible(true);
    }
}

textArea(文本域)

class MyFrame06 extends JFrame {
    public MyFrame06(String title) throws HeadlessException {
        super(title);
        setBounds(200,200,300,300);

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container container = this.getContentPane();
        container.setBackground(Color.BLUE);

        TextArea textArea = new TextArea(20, 20);
        textArea.setText("这是一个文本域");
        add(textArea);
        
        // 设置窗口可见度
        setVisible(true);
    }
}

TextArea(文本框)

class MyJFrame10 extends JFrame {
    public MyJFrame10(String title) throws HeadlessException {
        super(title);

        // 文本框
        TextArea textArea = new TextArea("text",20,20);
        // 可以配合滚动面板配合使用
        JScrollPane scrollPane = new JScrollPane(textArea);

        Container container = this.getContentPane();
        // 添加
        container.add(textArea);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,100,100);
        setVisible(true);
    }
}

JPasswordField(密码框)

class MyJFrame11 extends JFrame {
    public MyJFrame11(String title) throws HeadlessException {
        super(title);

        // 密码框
        JPasswordField jPasswordField = new JPasswordField();

        Container container = this.getContentPane();
        container.add(jPasswordField);
        setBounds(200,200,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

Button(按钮)

class MyJFrame04 extends JFrame {
    public MyJFrame04(String title) throws HeadlessException {
        super(title);
        setBounds(200,200,500,500);

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        Container container = this.getContentPane();
        container.setBackground(Color.CYAN);
        container.setLayout(new GridLayout(2,1));

        // 获取一个图片
        URL url = MyJFrame04.class.getResource("ico5.jpg");
        // 将一个图片转换为ico
        ImageIcon icon = new ImageIcon(url);

        JButton btn1 = new JButton("普通按钮");
        // 设置鼠标停留提示
        btn1.setToolTipText("这是一个普通按钮");
        JButton btn2 = new JButton("图片按钮");
        btn2.setToolTipText("这是一个图片按钮");
        // 设置鼠标停留提示
        // 将btn2按钮设置成图片按钮
        btn2.setIcon(icon);
        container.add(btn1);
        container.add(btn2);
        
        // 设置窗口可见度
        setVisible(true);
    }
}

JRadioButton(单选框)

class MyJFrame05 extends JFrame {
    public MyJFrame05(String title) throws HeadlessException {
        super(title);
        setBounds(200,200,300,300);
        setLayout(new GridLayout(2,1));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container container = this.getContentPane();

        // 单选框按钮
        JRadioButton jRadioButton1 = new JRadioButton("单选按钮1");
        JRadioButton jRadioButton2 = new JRadioButton("单选按钮2");
        // 由于单选按钮只能选择一个所以需要选项分组
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);

        // 添加
        container.add(jRadioButton1);
        container.add(jRadioButton2);

        // 设置窗口可见度
        setVisible(true);
    }
}

JCheckBox(多选框)

class MyJFrame06 extends JFrame {
    public MyJFrame06(String title) throws HeadlessException {
        super(title);

        // 复选框
        JCheckBox jCheckBox1 = new JCheckBox("复选框1");
        JCheckBox jCheckBox2 = new JCheckBox("复选框1");


        setBounds(200,200,300,300);
        setLayout(new GridLayout(2,1));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container container = this.getContentPane();
        container.setBackground(Color.BLUE);
        setVisible(true);

        // 添加
        container.add(jCheckBox1);
        container.add(jCheckBox2);
    }
}

JComboBox(下拉框)

class MyJFrame08 extends JFrame {
    public MyJFrame08(String title) throws HeadlessException {
        super(title);

        // 创建下拉框
        JComboBox jComboBox = new JComboBox();
        jComboBox.addItem("正在热映..");
        jComboBox.addItem("即将上映..");
        jComboBox.addItem("已下架..");
        jComboBox.addItem(null);

        Container container = this.getContentPane();
        container.add(jComboBox);
        container.setBackground(Color.GREEN);
        setBounds(200,200,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

JList(列表框)

class MyJFrame09 extends JFrame {
    public MyJFrame09(String title) throws HeadlessException {
        super(title);
        // 创建列表框
        // 生成列表内容
        String[] str = {"1","2","3"};

        // 创建列表框
        JList jList = new JList(str);

        Container container = this.getContentPane();
        container.add(jList);
        setBounds(200,200,300,300);
        setVisible(true);
        container.setBackground(Color.yellow);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

布局管理器

布局管理与AWT相似所以不在进行代码示例了。

FlowLayout(流式布局)

FlowLayout:组件向某个方向排列,遇到边界就折回,从头开始排列。

BorderLayout(东西南北中布局)

BorderLayout:将容器分为东,西,南,北,中五个区域普通组件被放置在这五个区域的任意一个中。注:这个布局不需要设置布局,只需添加组件时设置相应位置即可。

GridLayout(表格布局)

GridLayout:将容器分割成纵横线分隔的网格,每个网格所占的区域大小相同。

事件处理

概述:

Frame和组件本身没有事件处理的能力,必须由特定对象(事件监听器)来处理。
实现事件处理机制的步骤:

  1. 实现事件监听类,必须实现XxxListener接口。
  2. 创建普通组件(事件源),创建事件监听对象。
  3. 调用addXxxListener()方法,将事件监听器注册给普通组件,当事件源上发生指定的事件时,AWT会触发事件监听器,由事件监听器调用相应的方法(事件处理器)来处理事件,事件源上发生的事件会作为参数传入事件处理器。

鼠标监听

窗口监听

键盘监听

GUI小结

GUI


文章作者: 小靳同学
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小靳同学 !
评论
 上一篇
网络编程(54) 网络编程(54)
网络编程软件结构C/S结构 :全称为Client/Server结构,是指客户端和服务器结构。常见程序有QQ、迅雷等软件。 B/S结构
2021-10-18
下一篇 
注解(52) 注解(52)
注解 概念:说明程序的。给计算机看的 注释:用文字描述程序的。给程序员看的 定义:注解( Annotation),也叫元数据。一种代码级别
2021-10-13
  目录