面向对象程序设计

GUI

课堂练习

编写GUI程序,完成登录界面的设计。

(课堂使用流式布局,课后修改成绝对布局)

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.pujunming.nsusoft.GUIDemo;

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

/**
* Created by Intellij IDEA.
*
* @author Pu_Junming
* @create 2022/11/17 14:17
*/

public class LoginFrame extends JFrame implements ActionListener {
JTextField jTextField = new JTextField(20);
JPasswordField jPasswordField = new JPasswordField(20);
JButton button = new JButton("Login");
JLabel label1 = new JLabel("用户名");
JLabel label2 = new JLabel("密码");


public LoginFrame(){
this.setSize(700,200);
this.setLocation(700,400);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container cont = this.getContentPane();
cont.setLayout(new FlowLayout());
cont.add(label1);
cont.add(jTextField);
cont.add(label2);
cont.add(jPasswordField);
cont.add(button);

button.addActionListener(this);
}

public void actionPerformed(ActionEvent e){
String name = jTextField.getText();
String pwd = new String(jPasswordField.getPassword());
if (name.equals("pua") && pwd.equals("ktv")){
JOptionPane.showMessageDialog(this, "登录成功");
}else {
JOptionPane.showMessageDialog(this, "登录失败", "登录说明",JOptionPane.ERROR_MESSAGE);
}
}

public static void main(String[] args) {
new LoginFrame();
}
}

绝对布局练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.pujunming.nsusoft.GUIDemo;

import javax.swing.*;

/**
* Created by Intellij IDEA.
*
* @author Pu_Junming
* @create 2022/11/17 15:12
*/

// 绝对布局
public class Examplel {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello world!");
frame.setSize(350,200);
frame.setLocation(750,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 取消布局管理器
frame.setLayout(null);
//按钮
JButton button1 = new JButton("Login");
JButton button2 = new JButton("quit");
//button位置
button1.setBounds(40,60,100,30);
// button1.setLocation(40,60);
// button1.setSize(100,30);
button2.setBounds(180,60,100,30);
frame.add(button1);
frame.add(button2);


}
}