Java中的GUI库-----Swing

视频教程传送门https://www.bilibili.com/video/BV1t4411N7gK?p=2

Swing是Java中开发GUI的库

Java中窗体组件结构如下:

在这里插入图片描述

1. Swing常用组件

  • JFrame 窗体:有最大化、最小化和关闭

在这里插入图片描述

  • JDialog 对话框:只有关闭

在这里插入图片描述

  • JPanel 面板:啥都没有

    在这里插入图片描述

  • JButton 按钮

    在这里插入图片描述

  • JLabel 标签

    在这里插入图片描述

  • JCheckBox 多选按钮:多个选项,只能选择一个

    在这里插入图片描述

  • JTextField 文本框:只有一行

    在这里插入图片描述

  • JPassword 密码框:不显示输入

    在这里插入图片描述

  • JComBox 下拉框

    在这里插入图片描述

  • JTextArea 文本域:可以多行

    在这里插入图片描述

  • JList 列表框

    在这里插入图片描述

  • JOptionPane 小对话框

    在这里插入图片描述

2. 窗体操作

2.1 组件布局

2.1.1 绝对布局(nullLayout)

绝对布局使用坐标来控制组件的位置,窗体最大化或改变尺寸不会改变组件的位置,设置的是组件位置是以窗口左上角为(0,0),而窗口坐标是以屏幕左上角为原点

setLayout(null)

2.1.2 流布局(FlowLayout)

从左到右排列,默认居中对齐(可以设置左对齐和右对齐),排列方式和窗体大小有关

像水一样向某个方向流动,遇到障碍就折回

setLayout(new FlowLayout(对齐方式,水平间距,垂直间距))

2.1.3 边界布局(BorderLayout)

将容器划分为五个区域,默认添加到CENTER,同一个区域组件覆盖

在这里插入图片描述
add(button,BorderLayout.EAST)

2.1.4 网格布局(GridLayout)

将窗体分为多行多列的格子,如果组件个数大于网格个数,会自动优化

在这里插入图片描述
setLayout(new FlowLayout(行,列,水平间距,垂直间距))

2.1.5 网格组(包)布局管理器

先创建网格组对象和组件约束,然后设置容器对象为gridBag,最后给容器对象添加组建对象和约束对象

常用的组件约束属性包括:

  • 组件所在的位置:gridx,gridy

  • 组件占用的高度和宽度:gridwidth,gridheight

  • 组件所在的方位:anchor

    在这里插入图片描述

  • 组件的填充方式:fill,有BOTH、HORIZAONTAL、NULL和VERTICAL

  • 组件与单元格边缘的最小距离:insets(top, left, bottom, right)

  • 组件的首选大小:ipadx,ipady

  • 一个单元格最大的最大宽高:weightx,weighty

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

public class LayoutDemo extends JFrameDemo {
    
    
    public static void main(String[] args) {
    
    
        // set title
        JFrame f = new JFrame("JDialogDemo");
        // set size and location
        f.setSize(800,600);
        // 居中排列
        f.setLocationRelativeTo(null);
        // set background
        f.setBackground(Color.white);

        // get Container
        Container c = f.getContentPane();

        /**
         * 页面布局
         */
        // 使用绝对布局
//        c.setLayout(null);

        // 使用流布局,默认居中对齐,可以设置左对齐和右对齐
        // 右对齐:FlowLayout(FlowLayout.RIGHT)
        // 左对齐:FlowLayout(FlowLayout.LEFT)
        // 三个参数分别是:对齐方式、水平间距、垂直间距
//        c.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
//        for(int i=0; i<10; i++){
    
    
//            c.add(new JButton("按钮"+i));
//        }

        // 使用边界布局
//        c.setLayout(new BorderLayout());
//        c.add(button,BorderLayout.EAST);

        // 使用网格布局
//        c.setLayout(new GridLayout(3,3,10,10));
//        for(int i=0; i<10; i++){
    
    
//            c.add(new JButton("按钮"+i));
//        }

        // 使用网格组布局
        c.setLayout(new GridBagLayout());
        for(int i=0; i<9; i++){
    
    
            GridBagConstraints g = new GridBagConstraints();
            g.gridx = i;
            g.gridy = 0;
            c.add(new JButton("button"), g);
            GridBagConstraints q = new GridBagConstraints();
            q.gridx = 0;
            q.gridy = i;
            c.add(new JButton("button"), q);
        }

        // 创建约束条件
        GridBagConstraints g1 = new GridBagConstraints();
        g1.fill = GridBagConstraints.BOTH;
        g1.gridx = 1;
        g1.gridy = 1;
        g1.gridheight = 1;
        g1.gridwidth = 1;
        c.add(new JButton("button1"), g1);

        GridBagConstraints g2 = new GridBagConstraints();
//        g2.fill = GridBagConstraints.BOTH; // 水平垂直都填充
        g2.anchor = GridBagConstraints.NORTHEAST; // 组件在东北
        g2.gridx = 2;
        g2.gridy = 2;
        g2.gridwidth = 2;
        g2.gridheight = 1;
        c.add(new JButton("button2"), g2);

        GridBagConstraints g3 = new GridBagConstraints();
//        g3.fill = GridBagConstraints.VERTICAL; // 垂直填充
        // 组件离上下左右的位置
        g3.insets = new Insets(5,10,5,10);

        g3.gridx = 4;
        g3.gridy = 3;
        g3.gridwidth = 2;
        g3.gridheight = 2;
        c.add(new JButton("button3"), g3);




        // 创建按钮
//        JButton button = new JButton("login");
        // 设置按钮位置
//        button.setBounds(50,50,100,50);
//        c.add(button);

        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

2.2 JFrame窗体

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

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        // 创建窗体
        JFrame f = new JFrame("this is a demo");
        // 显示窗体
        f.setVisible(true);

        /*
         * EXIT_ON_CLOSE: 设置关闭窗体时停止程序
         * DO_NOTHING_ON_CLOSE: 关闭窗体时无操作
         * DISPOSE_ON_CLOSE: 关闭时释放窗体资源
         * HIDE_ON_CLOSE: 关闭时隐藏窗口但不停止程序
         */

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//        // 设置窗体大小,单位像素
//        f.setSize(400, 300);
//        // 设置窗体出现位置
//        f.setLocation(222,333);
        // 合并设置窗体大小和位置,坐标x,y 大小width, height
        f.setBounds(444,222,400,300);
        // 固定窗体大小
        f.setResizable(false);
        // 获取窗体位置
        System.out.println("x:"+f.getX()+"  y:"+f.getY());

        // 获取窗体容器
        Container c = f.getContentPane();
        // 设置背景颜色
        c.setBackground(Color.lightGray);
        // 窗体中添加组件
        JLabel l = new JLabel("this is a label");
        c.add(l);
        // 删除组件
        c.remove(l);
        // 验证容器中组件,相当于刷新操作
        c.validate();
        // 窗体重新载入容器
        f.setContentPane(c);
    }
}

在实际应用中会让窗体类继承自JFrame,然后重写构造方法。如

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

/**
 * Title: JFrame操作
 * Description: JFrame窗体设置,以及添加组件
 * Filename: JFrameDemo.java
 */
public class JFrameDemo extends JFrame{
    
    
    public static void main(String[] args) {
    
    
        new JFrameDemo();
    }
    public JFrameDemo(){
    
    
        // 设置标题
        setTitle("this is a demo");
        // 显示窗体
        setVisible(true);

        /*
         * EXIT_ON_CLOSE: 设置关闭窗体时停止程序
         * DO_NOTHING_ON_CLOSE: 关闭窗体时无操作
         * DISPOSE_ON_CLOSE: 关闭时释放窗体资源
         * HIDE_ON_CLOSE: 关闭时隐藏窗口但不停止程序
         */
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // 设置窗体大小,单位像素
//        f.setSize(400, 300);
        // 设置窗体出现位置
//        f.setLocation(222,333);
        // 合并设置窗体大小和位置,坐标x,y(左上角的坐标) 大小width, height
        setBounds(444,222,800,600);
        // 固定窗体大小
        setResizable(false);
        // 获取窗体位置
        System.out.println("x:"+getX()+"  y:"+getY());

        // 获取窗体容器
        Container c = getContentPane();
        // 设置背景颜色
        c.setBackground(Color.lightGray);
        c.setLayout(null);

        /**
         * Label
         */
        // 窗体中添加组件
        JLabel l = new JLabel("this is a label");
        // 更改标签内容
//        l.setText("Text changed");
        // 获取标签内容
//        System.out.println(l.getText());

        // 设置字体样式
        l.setFont(new Font("New Times Romma", Font.BOLD,15));
        // 设置标签颜色
        l.setForeground(Color.RED);

        // 添加图片,默认获取项目的路径
        ImageIcon icon = new ImageIcon("src/test2/image/off.png");
//        通过URL获取图片
//        URL url = JFrameDemo.class.getResource("image/off.png");
//        ImageIcon icon = new ImageIcon(url);
        l.setIcon(icon);

//        c.add(l);
        // 删除组件
//        c.remove(l);

        /**
         * 下拉框
         */
//        方法1
//        JComboBox<Object> jc = new JComboBox<>();
//        jc.addItem("身份证");
//        jc.addItem("学生证");
//        jc.addItem("工作证");

//        方法2
//        String[] item = {"身份证","学生证","工作证"};
//        JComboBox<String> jc = new JComboBox<>(item);

//        方法3
        JComboBox<String> jc = new JComboBox<>();
        String[] item = {
    
    "身份证","学生证","工作证"};
        DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(item);
        jc.setModel(model);

//        打印选中的索引
        JButton b = new JButton("print");
        b.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                System.out.println("选中的索引:"+jc.getSelectedIndex());
                System.out.println("选中的值:"+jc.getSelectedItem());
            }
        });
        // 下拉列表值是否可以编辑
        jc.setEditable(true);

        jc.setBounds(10,10,80,21);
        b.setBounds(100,10,80,21);
        c.add(b);
        c.add(jc);

        /**
         * 列表框
         */
        String[] is = {
    
    "身份证","学生证","工作证"};
        JList<String> jl = new JList<>(is);
        /*
         * 选择模式,有三种:
         * SINGLE_SELECTION,MULTIPLE_INTERVAL_SELECTION,SINGLE_INTERVAL_SELECTION
         */
        jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        // 给列表添加滚动条
        JScrollPane js = new JScrollPane(jl);
//        打印选中的索引
        JButton b1 = new JButton("show");
        b1.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                List<String> values = jl.getSelectedValuesList();
                for(String value : values){
    
    
                    System.out.println(value);
                }
            }
        });
        b1.setBounds(300,10,80,21);
        c.add(b1);
        js.setBounds(200, 10, 80,40);
        c.add(js);

        /**
         * 文本框
         */
        JTextField jt = new JTextField();
        jt.setColumns(20); // 设置文本框长度
        jt.setText("这是文本框"); // 设置文本
        jt.setFont(new Font("黑体", Font.PLAIN, 16)); // 设置字体格式

        // 获得文本框中的值
        JButton b3 = new JButton("确认");
        b3.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                System.out.println(jt.getText());
                jt.setText(""); // 清空文本框内容
            }
        });
        b3.setBounds(400,40,80,20);
        c.add(b3);
        jt.setBounds(400,10, 100,20);
        c.add(jt);

        // 验证容器中组件,相当于刷新操作
        c.validate();
        // 窗体重新载入容器
        setContentPane(c);
    }
}

2.3 JDialog窗体

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

public class JDialogDemo extends JDialog {
    
    
    public static void main(String[] args) {
    
    
        // set title
        JFrame f = new JFrame("JDialogDemo");
        // set size and location
        f.setBounds(0,0,300,300);
        // set background
        f.setBackground(Color.white);

        // get Container
        Container c = f.getContentPane();

        // 使用绝对布局
        c.setLayout(null);

        // 创建按钮
        JButton button = new JButton("login");
        // 设置按钮位置
        button.setBounds(50,50,100,50);
        c.add(button);


        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 添加动作监听
        button.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                JDialogDemo d = new JDialogDemo(f);
                d.setVisible(true);
            }
        });


    }

    // 重写构造方法
    public JDialogDemo(JFrame frame){
    
    
        // 父窗体,JDialog名称,是否阻塞父窗体(弹出子窗口时是否可以操作父窗口)
        super(frame,"Login", true);

        // 获取容器
        Container c = getContentPane();

        setBounds(300,200,300,200);

    }
}

猜你喜欢

转载自blog.csdn.net/qq_24852439/article/details/105225482