jframe写登陆界面
时间: 2023-06-22 20:31:49 浏览: 55
好的,下面是一个简单的 Jframe 登录界面的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
private JLabel userLabel, passwordLabel;
private JTextField userTextField;
private JPasswordField passwordField;
private JButton loginButton;
public LoginFrame() {
setTitle("登录");
setSize(300, 200);
setLocationRelativeTo(null);
// 创建组件
userLabel = new JLabel("用户名:");
passwordLabel = new JLabel("密 码:");
userTextField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("登录");
// 设置布局
setLayout(new GridLayout(3, 1));
// 添加组件
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel1.add(userLabel);
panel1.add(userTextField);
add(panel1);
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel2.add(passwordLabel);
panel2.add(passwordField);
add(panel2);
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel3.add(loginButton);
add(panel3);
// 添加事件监听
loginButton.addActionListener(this);
passwordField.addActionListener(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton || e.getSource() == passwordField) {
String username = userTextField.getText();
String password = new String(passwordField.getPassword());
// 在这里进行登录验证
// 如果用户名和密码正确,就打开主窗口
// 如果用户名或密码错误,就显示错误提示信息
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
运行程序后,会显示一个登录界面,包含一个用户名文本框、一个密码文本框和一个登录按钮。当用户点击登录按钮或密码文本框时,程序会获取用户名和密码,并进行登录验证。如果用户名和密码正确,就可以打开主窗口;如果用户名或密码错误,就会显示错误提示信息。在 `actionPerformed()` 方法中的登录验证部分,你可以实现自己的登录验证逻辑。