用JAVA创建一个登录窗口
时间: 2024-05-08 14:14:54 浏览: 7
以下是使用Java Swing创建一个简单的登录窗口的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginWindow extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
public LoginWindow() {
setTitle("登录");
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 创建面板
JPanel panel = new JPanel(new GridLayout(3, 2));
// 添加组件
JLabel usernameLabel = new JLabel("用户名:");
panel.add(usernameLabel);
usernameField = new JTextField();
panel.add(usernameField);
JLabel passwordLabel = new JLabel("密码:");
panel.add(passwordLabel);
passwordField = new JPasswordField();
panel.add(passwordField);
JButton loginButton = new JButton("登录");
loginButton.addActionListener(this);
panel.add(loginButton);
JButton cancelButton = new JButton("取消");
cancelButton.addActionListener(this);
panel.add(cancelButton);
// 添加面板到窗口
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("登录")) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// TODO: 检查用户名和密码是否正确
} else if (e.getActionCommand().equals("取消")) {
dispose();
}
}
public static void main(String[] args) {
new LoginWindow();
}
}
```
这个窗口包含一个文本框和一个密码框,以及两个按钮:一个用于登录,一个用于取消。当用户单击登录按钮时,程序将获取文本框和密码框中的值,并执行某些操作(例如检查用户名和密码是否正确)。如果用户单击取消按钮,程序将关闭窗口。