用Java写一个登录界面,需要有账号密码,以及登录和取消按钮
时间: 2024-03-17 14:46:12 浏览: 13
好的,以下是一个简单的Java登录界面的代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
public LoginFrame() {
super("登录");
// 创建组件
JLabel usernameLabel = new JLabel("账号:");
JLabel passwordLabel = new JLabel("密码:");
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
JButton loginButton = new JButton("登录");
JButton cancelButton = new JButton("取消");
// 设置布局
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(loginButton);
panel.add(cancelButton);
this.add(panel);
// 添加事件监听器
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
// 设置窗口属性
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("登录")) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// TODO: 检查用户名和密码是否正确
JOptionPane.showMessageDialog(this, "登录成功!");
} else if (e.getActionCommand().equals("取消")) {
System.exit(0);
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
运行这个程序会显示一个登录窗口,包含一个账号输入框、一个密码输入框、一个登录按钮和一个取消按钮。当用户点击登录按钮时,程序会读取输入框中的用户名和密码,并检查其是否正确;如果正确,则弹出一个提示框,显示“登录成功!”消息。如果用户点击取消按钮,则程序退出。