使用java写一个登录页面
时间: 2024-05-15 16:16:53 浏览: 8
以下是一个简单的Java登录页面示例,使用Swing GUI库:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login extends JFrame implements ActionListener {
private JLabel titleLabel, userLabel, passLabel;
private JTextField userField;
private JPasswordField passField;
private JButton loginButton, cancelButton;
public Login() {
setTitle("登录");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建组件
titleLabel = new JLabel("用户登录");
titleLabel.setFont(new Font("宋体", Font.BOLD, 20));
userLabel = new JLabel("用户名:");
passLabel = new JLabel("密 码:");
userField = new JTextField(10);
passField = new JPasswordField(10);
loginButton = new JButton("登录");
cancelButton = new JButton("取消");
// 设置布局
setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.add(userLabel);
panel.add(userField);
panel.add(passLabel);
panel.add(passField);
panel.add(loginButton);
panel.add(cancelButton);
add(titleLabel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
// 添加事件监听器
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String user = userField.getText();
String pass = new String(passField.getPassword());
// 进行登录验证,例如:
if (user.equals("admin") && pass.equals("123456")) {
JOptionPane.showMessageDialog(this, "登录成功!");
dispose(); // 关闭登录窗口
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
}
} else if (e.getSource() == cancelButton) {
dispose(); // 关闭登录窗口
}
}
public static void main(String[] args) {
new Login();
}
}
```
运行该程序,将显示一个登录窗口,用户可以输入用户名和密码,点击“登录”按钮进行验证,或者点击“取消”按钮关闭窗口。如果用户名和密码匹配,则提示登录成功,否则提示错误信息。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)