观察并模仿Demo启动登录类窗口的代码java
时间: 2024-03-01 09:51:01 浏览: 15
好的,以下是一个简单的启动登录类窗口的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginWindow {
private JFrame frame;
private JLabel label_username;
private JTextField text_username;
private JLabel label_password;
private JPasswordField text_password;
private JButton button_login;
public LoginWindow() {
frame = new JFrame("Login");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2));
label_username = new JLabel("Username:");
text_username = new JTextField(20);
label_password = new JLabel("Password:");
text_password = new JPasswordField(20);
button_login = new JButton("Login");
frame.add(label_username);
frame.add(text_username);
frame.add(label_password);
frame.add(text_password);
frame.add(button_login);
button_login.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 在这里添加登录验证逻辑
// 这里只做演示用,直接验证用户名和密码是否为空
String username = text_username.getText();
String password = String.valueOf(text_password.getPassword());
if (username.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please enter username and password.", "Error", JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(frame, "Login success.", "Success", JOptionPane.INFORMATION_MESSAGE);
}
}
});
frame.setVisible(true);
}
public static void main(String[] args) {
new LoginWindow();
}
}
```
运行以上代码后,会弹出一个简单的登录窗口,用户输入用户名和密码后,点击登录按钮,可以触发登录验证逻辑。这里的验证逻辑只是简单地判断用户名和密码是否为空,并没有实际的验证功能。你可以根据实际需求进行修改。