视频教程传送门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 =