視頻教程傳送門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);
}
}