简介
- AWT(译:抽象窗口工具包),是Java的平台独立的窗口系统,图形和用户界面器件工具包。
- Swing 是为了解决 AWT 存在的问题而以 AWT 为基础新开发的包(在使用Swing时也常会用到java.awt.*包)。
JFrame
JFrame容器允许程序员把其他组件添加到它里面,把它们组织起来,并把它们呈现给用户。我们可以直接new一个JFrame对象,也可以自己实现一个类继承它(常用)。
常用方法
- 设置窗口可见:setVisible(true);//默认为false
- 设置窗口标题;setTitle(String title)
- 设置点击窗口的×后执行的操作:setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
各参数定义:
EXIT_ON_CLOSE 隐藏窗口,并退出程序
DO_NOTHING_ON_CLOSE 无任何操作
HIDE_ON_CLOSE 隐藏窗体,但不停止程序
DISPOSE_ON_CLOSE 释放窗体资源
- 设置窗体的大小(单位:像素):setSize(int width, int height);
- 设置窗体坐标(单位:像素):setLocation(int x, int y);
- 坐标大小一起设置:setBounds(int x, int y, int width, int height);
- 获取窗口坐标:横坐标:getX();纵坐标:getY()
- 获取窗口大小:宽:getWidth();高:getHeight()
- 获取窗口容器:Container contentPane = getContentPane();
设置背景:contentPane.setBackground(Color.GREEN)
添加组件:contentPane.add(Component comp)
验证容器中的组件(相当于刷新):contentPane.validate()
重新载入容器可实现刷新效果:setContentPane(contentPane) //一般使用validate()
设置布局:contentPane.setLayout(LayoutManager mgr);
常见组件
按钮:JButton
复选框组件:JCheckbox
下拉列表框:JCombox
标签组件:JLabel
单选按钮:JRadioButton
框列表框:JList
文本框:JTextField
密码框:JPasswordField
文本域:JTextArea
对话框:JOptionPane
代码示例
JDialog对话框
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7
8 /**
9 * 对话框
10 */
11 public class Demo02 extends JDialog {
12
13 public Demo02(JFrame jFrame) {
14 /**
15 * 父窗体对象,对话框标题, 是否阻塞父窗体(只能弹出一个对话框,弹出后不能点击父窗体)
16 */
17 super(jFrame, "对话框标题", true);
18 Container contentPane = getContentPane();
19 contentPane.add(new JLabel("这是一个对话框"));
20 setBounds(300, 300, 300, 300);
21 }
22
23 public static void main(String[] args) {
24 JFrame jFrame = new JFrame("父窗体");
25 jFrame.setBounds(200,200,500,500);
26 Container contentPane = jFrame.getContentPane();
27 JButton button = new JButton("弹出对话框");
28 //设置布局,使用流布局
29 contentPane.setLayout(new FlowLayout());
30 contentPane.add(button);
31 jFrame.setVisible(true);
32 jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
33
34 // button.addActionListener(new ActionListener() {
35 // @Override
36 // public void actionPerformed(ActionEvent e) {
37 // Demo02 demo02 = new Demo02(jFrame);
38 // //设置对话框可见
39 // demo02.setVisible(true);
40 // }
41 // });
42
43 //Lambda 表达式
44 button.addActionListener((e)->{
45 Demo02 demo02 = new Demo02(jFrame);
46 //设置对话框可见
47 demo02.setVisible(true);
48 });
49
50 }
51 }
View Code
使用JLabel标签添加图片
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.net.URL;
6
7 /**
8 * 使用JLabel标签添加图片
9 */
10 public class Demo03 extends JFrame {
11 public Demo03(){
12 setTitle("显示图片窗口");
13 setVisible(true);
14 setBounds(300, 300, 400, 400);
15 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16 Container contentPane = getContentPane();
17
18 contentPane.setBackground(Color.cyan);
19
20 JLabel jLabel = new JLabel();
21 // URL url = Demo03.class.getResource("/picture.jpg");
22 // //获取相应路径下的图片
23 // Icon icon = new ImageIcon(url);
24
25 ImageIcon icon = new ImageIcon("src/picture.jpg");
26 System.out.println(icon.getIconHeight()+"#"+icon.getIconWidth());
27 //使图片适应窗口
28 icon.setImage(icon.getImage().getScaledInstance(getWidth(), getHeight(), Image.SCALE_DEFAULT));
29 //添加图片
30 jLabel.setIcon(icon);
31 // 即使设置标签大小,也不会改变图片大小
32 // jLabel.setSize(20, 20);
33
34 System.out.println(icon.getIconHeight()+"#"+icon.getIconWidth());
35
36 contentPane.add(jLabel);
37 //刷新
38 contentPane.validate();
39 }
40
41 public static void main(String[] args) {
42 new Demo03();
43 }
44 }
View Code
设置布局
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5
6 /**
7 * 设置布局
8 */
9 public class Demo04 extends JFrame {
10
11 public Demo04(){
12 setTitle("布局");
13 setBounds(300, 300, 400, 400);
14 setVisible(true);
15 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16
17 Container contentPane = getContentPane();
18 /**
19 * 绝对布局(参数为null时为绝对布局),即各组件位置按像素设定
20 * 各组件位置大小不会随窗口改变而该变
21 *
22 contentPane.setLayout(null);
23 JButton bb = new JButton("按钮1");
24 JButton bb2 = new JButton("按钮2");
25 // 设置组件在窗体位置及大小(不设置无法显示)
26 bb.setBounds(10, 10,100,100);
27 bb2.setBounds(200, 200,100,100);
28 contentPane.add(bb);
29 contentPane.add(bb2);
30 */
31 /**
32 * 设置布局,不设置默认边界布局
33 * 使用流布局(组件会随窗体大小而改变),不传参数默认居中对齐,
34 * 参数:对齐方式、水平间距、垂直间距
35 *
36
37 contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 30));
38 for (int i = 0; i < 10; i++){
39 contentPane.add(new JButton("b"+i));
40 }
41 */
42 /**
43 //使用边界布局
44 contentPane.setLayout(new BorderLayout());
45 JButton b1 = new JButton("中"),
46 b2 = new JButton("东"),
47 b3 = new JButton("西"),
48 b4 = new JButton("南"),
49 b5 = new JButton("北");
50 //中部添加(不指明方位默认为中部)
51 contentPane.add(b1, BorderLayout.CENTER);
52 //东部
53 contentPane.add(b2, BorderLayout.EAST);
54 //西部
55 contentPane.add(b3, BorderLayout.WEST);
56 //南部
57 contentPane.add(b4, BorderLayout.SOUTH);
58 //北部
59 contentPane.add(b5, BorderLayout.NORTH);
60 //新组件会覆盖旧组件
61 contentPane.add(new JButton("覆盖"), BorderLayout.NORTH);
62
63 */
64
65 /**
66 * 网格布局GridLayout(行数, 列数,列距,行距)(列距,行距可省略,默认为0)
67
68 contentPane.setLayout(new GridLayout(4, 5,5,10));
69 for (int i=0; i < 20; i++){
70 contentPane.add(new JButton("按钮"+i));
71 }
72 //超过规格会自动扩充适应
73 contentPane.add(new JButton("超过的按钮"));
74 */
75
76 //刷新
77 contentPane.validate();
78 }
79
80 public static void main(String[] args) {
81 new Demo04();
82 }
83 }
View Code
网格组布局管理
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5
6 /**
7 * 网格组布局管理
8 */
9 public class Demo05 {
10 JFrame jFrame = new JFrame();
11 Container container;
12 void createFrame(){
13 //设置网格组布局
14 container = jFrame.getContentPane();
15 container.setLayout(new GridBagLayout());
16 jFrame.setSize(800, 600);
17 //先设置大小再设置默认居中
18 // jFrame.setLocationRelativeTo(null);
19 jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20 }
21 void init(){
22 //创建约束条件
23 GridBagConstraints g1 = new GridBagConstraints();
24 //第一行第一列
25 g1.gridx = 0;
26 g1.gridy = 0;
27 container.add(new JButton("组件1"), g1);
28 GridBagConstraints g2 = new GridBagConstraints();
29 //第二行第二列
30 g2.gridx = 1;
31 g2.gridy = 1;
32 container.add(new JButton("组件2"), g2);
33 GridBagConstraints g3 = new GridBagConstraints();
34 //第四行第四列(由于第三行第三列没组件,自动补齐)
35 g3.gridx = 3;
36 g3.gridy = 3;
37 container.add(new JButton("组件3"), g3);
38 }
39
40 void init2(){
41 //创建约束条件
42 GridBagConstraints g1 = new GridBagConstraints();
43 //第一行第一列
44 g1.gridx = 1;
45 g1.gridy = 1;
46 //宽高各占一格
47 g1.gridwidth = 1;
48 g1.gridheight = 1;
49 container.add(new JButton("none"), g1);
50 GridBagConstraints g2 = new GridBagConstraints();
51 //第二行第二列
52 g2.gridx = 2;
53 g2.gridy = 1;
54 g2.gridwidth = 2;
55 g2.gridheight = 1;
56 //水平填充
57 g2.fill = GridBagConstraints.HORIZONTAL;
58 container.add(new JButton("HORIZONTAL"), g2);
59 GridBagConstraints g3 = new GridBagConstraints();
60 //第四行第四列(由于第三行第三列没组件,自动补齐)
61 g3.gridx = 4;
62 g3.gridy = 1;
63 g3.gridwidth = 2;
64 g3.gridheight = 2;
65 //垂直填充
66 g3.fill = GridBagConstraints.VERTICAL;
67 container.add(new JButton("VERTICAL"), g3);
68 GridBagConstraints g4 = new GridBagConstraints();
69 //第四行第四列(由于第三行第三列没组件,自动补齐)
70 g4.gridx = 6;
71 g4.gridy = 1;
72 g4.gridwidth = 2;
73 g4.gridheight = 2;
74 //全填充
75 g4.fill = GridBagConstraints.BOTH;
76 container.add(new JButton("BOTH"), g4);
77 }
78
79 /**
80 * anchor属性(确定方位,默认CENTER居中)
81 */
82 void init3(){
83 //创建约束条件
84 GridBagConstraints g1 = new GridBagConstraints();
85 //第一行第一列
86 g1.gridx = 1;
87 g1.gridy = 1;
88 g1.gridheight = 2;
89 g1.gridwidth = 2;
90 g1.anchor = GridBagConstraints.NORTHEAST;
91 container.add(new JButton("@"), g1);
92 //创建面板
93 // g1.anchor = GridBagConstraints.CENTER;
94 g1.fill = GridBagConstraints.BOTH;
95 JPanel jPanel = new JPanel();
96 jPanel.setBackground(Color.green);
97 container.add(jPanel, g1);
98 }
99
100 /**
101 * insert自定义位置
102 */
103 void init4(){
104 //创建约束条件
105 GridBagConstraints g1 = new GridBagConstraints();
106 //第一行第一列
107 g1.gridx = 1;
108 g1.gridy = 1;
109 g1.insets = new Insets(5,5,5,10);
110 container.add(new JButton("@"), g1);
111
112 }
113 /**
114 * ipadx和ipady组件的首选大小(正数放大,负数缩小)
115 */
116 void init5(){
117 //创建约束条件
118 GridBagConstraints g1 = new GridBagConstraints();
119 //第一行第一列
120 g1.gridx = 1;
121 g1.gridy = 1;
122 g1.ipadx = 100;
123 g1.ipady = 10;
124 container.add(new JButton("@"), g1);
125
126 GridBagConstraints g2 = new GridBagConstraints();
127 g2.gridx = 4;
128 g2.gridy = 2;
129 g2.ipadx = -10;
130 g2.ipady = -10;
131 container.add(new JButton("@"), g2);
132
133 }
134
135 /**
136 * weightx,weighty用来设置窗口变大时,各组件跟着变大的比例
137 * 窗体放大时组件2的x轴放大倍速是组件1的10倍
138 */
139 void init6(){
140 //创建约束条件
141 GridBagConstraints g1 = new GridBagConstraints();
142 //第一行第一列
143 g1.gridx = 1;
144 g1.gridy = 1;
145 g1.weightx = 0.1;
146 g1.weighty = 0.5;
147 container.add(new JButton("组件1"), g1);
148
149 GridBagConstraints g2 = new GridBagConstraints();
150 //第一行第一列
151 g2.gridx = 2;
152 g2.gridy = 1;
153 g2.weightx = 1;
154 g2.weighty = 0.5;
155 container.add(new JButton("组件2"), g2);
156
157 }
158 void createButton(){
159 for (int i=0; i<10; i++){
160 GridBagConstraints gg = new GridBagConstraints();
161 gg.gridx = i;
162 gg.gridy = 0;
163 container.add(new JButton("网格"), gg);
164 }
165 for (int i=0; i<10; i++){
166 GridBagConstraints gg2 = new GridBagConstraints();
167 gg2.gridx = 0;
168 gg2.gridy = i;
169 container.add(new JButton("网格"), gg2);
170 }
171
172 }
173 public static void main(String[] args) {
174 Demo05 demo05 = new Demo05();
175 demo05.createFrame();
176 demo05.createButton();
177 demo05.init6();
178 demo05.jFrame.setVisible(true);
179 }
180 }
View Code
下拉列表(JComboBox)
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7
8 /**
9 * 下拉列表(JComboBox)
10 */
11 public class Demo06 extends JFrame {
12 public Demo06(){
13 setBounds(200,200, 400, 400);
14 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15
16 Container contentPane = getContentPane();
17 contentPane.setLayout(null);
18
19 //下拉框
20 //向下拉框添加选项一
21 // JComboBox<String> jComboBox = new JComboBox<>();
22 // jComboBox.addItem("苹果");
23 // jComboBox.addItem("荔枝");
24 // jComboBox.addItem("桃");
25 //向下拉框添加选项二(用String数组)
26 // String items[] = new String[]{"苹果","荔枝","芒果"};
27 // JComboBox<String> jComboBox = new JComboBox<>(items);
28
29 //向下拉框添加选项三(下拉列表模型)
30 JComboBox<String> jComboBox = new JComboBox<>();
31 String items[] = new String[]{"苹果","荔枝","芒果"};
32 ComboBoxModel<String> comboBoxModel = new DefaultComboBoxModel<>(items);
33 jComboBox.setModel(comboBoxModel);
34 //设置是否可输入(默认false)输入后获取的下标为-1
35 jComboBox.setEditable(true);
36
37 jComboBox.setBounds(100, 100, 100, 30);
38
39
40 JButton jButton = new JButton("打印");
41 jButton.setBounds(200, 100, 100, 30);
42 jButton.addActionListener(new ActionListener() {
43 @Override
44 public void actionPerformed(ActionEvent e) {
45 System.out.println("选中项下标:"+jComboBox.getSelectedIndex());
46 System.out.println("选中项:"+jComboBox.getSelectedItem());
47 }
48 });
49
50
51 contentPane.add(jButton);
52 contentPane.add(jComboBox);
53 setVisible(true);
54 }
55
56 public static void main(String[] args) {
57 new Demo06();
58 }
59 }
View Code
列表框JList
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7 import java.util.List;
8
9 /**
10 * 列表框JList
11 */
12 public class Demo07 extends JFrame {
13 public Demo07(){
14 setBounds(200,200, 400, 400);
15 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16 Container contentPane = getContentPane();
17 contentPane.setLayout(null);
18
19 String[] items = new String[]{"a", "b", "c", "d", "e", "f", "g"};
20 //创建列表数据的模型
21 DefaultListModel<String> defaultListModel = new DefaultListModel<>();
22 for (String tem: items){
23 //向列表模型添加元素
24 defaultListModel.addElement(tem);
25 }
26 //列表
27 JList<String> jList = new JList<>();
28 jList.setModel(defaultListModel);
29
30 /**
31 * 设置选择模式
32 * MULTIPLE_INTERVAL_SELECTION:(默认)随便选
33 * SINGLE_INTERVAL_SELECTION:只能选择相邻的元素
34 * SINGLE_SELECTION:单选
35 */
36 jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
37
38 //创建滚动条并添加列表
39 JScrollPane jScrollPane = new JScrollPane(jList);
40 jScrollPane.setBounds(100, 100, 100, 100);
41
42 //使用模型可随时添加元素
43 defaultListModel.addElement("添加元素");
44
45 contentPane.add(jScrollPane);
46 setVisible(true);
47
48 JButton jButton = new JButton("打印");
49 jButton.setBounds(200,100,100,30);
50 jButton.addActionListener(new ActionListener() {
51 @Override
52 public void actionPerformed(ActionEvent e) {
53 List<String> selectedValuesList = jList.getSelectedValuesList();
54 for (String tmp: selectedValuesList){
55 System.out.println(tmp);
56 }
57 System.out.println("_______end________");
58 }
59 });
60
61 contentPane.add(jButton);
62 }
63
64 public static void main(String[] args) {
65 new Demo07();
66 }
67 }
View Code
文本框JTextField
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7
8 /**
9 * 文本框JTextField
10 */
11 public class Demo08 extends JFrame {
12 public Demo08(){
13 setBounds(100, 100, 400, 200);
14 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15 Container contentPane = getContentPane();
16 contentPane.setLayout(new FlowLayout());
17
18 //创建文本框
19 JTextField jTextField = new JTextField();
20 //设置文本框长度(单位字符)
21 jTextField.setColumns(20);
22 //设置初始值
23 jTextField.setText("初始值");
24 //设置字体格式
25 jTextField.setFont(new Font("黑体", Font.PLAIN,20));
26
27
28 contentPane.add(jTextField);
29
30 JButton jButton = new JButton("确认");
31 jButton.addActionListener(new ActionListener() {
32 @Override
33 public void actionPerformed(ActionEvent e) {
34 System.out.println("文本框的内容:"+jTextField.getText());
35 //清空文本框
36 jTextField.setText("");
37 //获取焦点
38 jTextField.requestFocus();
39 }
40 });
41
42 contentPane.add(jButton);
43 setVisible(true);
44 }
45
46 public static void main(String[] args) {
47 new Demo08();
48 }
49 }
View Code
密码框
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7
8 /**
9 * 密码框
10 */
11 public class Demo09 extends JFrame {
12 public Demo09(){
13 setBounds(200, 200, 400, 100);
14 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15 Container contentPane = getContentPane();
16 contentPane.setLayout(new FlowLayout());
17
18 //创建密码框组件
19 JPasswordField jPasswordField = new JPasswordField();
20 //设置密码框长度,20个字符
21 jPasswordField.setColumns(20);
22
23 //设置回显字符(屏幕上看到我们输入的字符)
24 jPasswordField.setEchoChar('#');
25 //设置字体
26 jPasswordField.setFont(new Font("黑体", Font.BOLD, 18));
27
28 //添加监听(回车时触发)
29 jPasswordField.addActionListener(new ActionListener() {
30 @Override
31 public void actionPerformed(ActionEvent e) {
32 char[] password = jPasswordField.getPassword();
33 System.out.println(new String(password));
34 }
35 });
36
37 contentPane.add(jPasswordField);
38
39 setVisible(true);
40
41 }
42
43 public static void main(String[] args) {
44 new Demo09();
45 }
46 }
View Code
文本域
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5
6 /**
7 * 文本域
8 */
9 public class Demo10 extends JFrame {
10 public Demo10(){
11 setBounds(200, 200, 400, 400);
12 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13 Container contentPane = getContentPane();
14 contentPane.setLayout(new FlowLayout());
15
16 //创建文本域
17 JTextArea jTextArea = new JTextArea();
18 //设定文本内容
19 jTextArea.setText("初始内容");
20 //设定行
21 jTextArea.setRows(5);
22 //设定列数
23 jTextArea.setColumns(20);
24 //添加内容
25 jTextArea.append("添加内容");
26 //在第二个字符后面插入内容
27 jTextArea.insert("【插入内容】", 2);
28 //给文本域添加滚动条
29 JScrollPane jScrollPane = new JScrollPane(jTextArea);
30 contentPane.add(jScrollPane);
31 setVisible(true);
32 }
33
34 public static void main(String[] args) {
35 new Demo10();
36 }
37 }
View Code
事件监听
1 package com.czm;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7 import java.awt.event.FocusEvent;
8 import java.awt.event.FocusListener;
9
10 /**
11 * 事件监听
12 */
13 public class Demo11 extends JFrame {
14 public Demo11(){
15 setBounds(200, 200, 400, 400);
16 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17 Container contentPane = getContentPane();
18 contentPane.setLayout(new FlowLayout());
19
20
21 JLabel jLabel = new JLabel("标签");
22 JButton jButton = new JButton("按钮");
23 jButton.addActionListener(new ActionListener() {
24 @Override
25 public void actionPerformed(ActionEvent e) {
26 jLabel.setText("按钮被点击");
27 }
28 });
29
30 JTextField jTextField = new JTextField();
31 //设置文本框长度(单位字符)
32 jTextField.setColumns(20);
33 //设置初始值
34 jTextField.setText("初始值");
35 //设置字体格式
36 jTextField.setFont(new Font("黑体", Font.PLAIN,20));
37
38 jTextField.addFocusListener(new MyFocusListenter());
39
40 // jTextField.addFocusListener(new FocusListener() {
41 // @Override
42 // public void focusGained(FocusEvent e) {
43 //
44 // }
45 //
46 // @Override
47 // public void focusLost(FocusEvent e) {
48 //
49 // }
50 // });
51
52 contentPane.add(jTextField);
53 contentPane.add(jLabel);
54 contentPane.add(jButton);
55 setVisible(true);
56 }
57
58 //实现焦点事件监听器
59 class MyFocusListenter implements FocusListener{
60 //获取焦点
61 @Override
62 public void focusGained(FocusEvent e) {
63 //获取触发事件的文本框
64 JTextField source = (JTextField) e.getSource();
65 //给获取焦点的文本框设置绿色边框
66 source.setBorder(BorderFactory.createLineBorder(Color.green));
67 source.setText("获得焦点");
68 }
69
70 //离焦
71 @Override
72 public void focusLost(FocusEvent e) {
73 //获取触发事件的文本框
74 JTextField source = (JTextField) e.getSource();
75 //给失去焦点的文本框设置绿色边框
76 source.setBorder(BorderFactory.createLineBorder(Color.red));
77 source.setText("失去焦点");
78 }
79 }
80 public static void main(String[] args) {
81 new Demo11();
82 }
83 }
View Code