使用java实现一个登录页demo
时间: 2024-05-05 22:15:35 浏览: 12
以下是Java实现的登录页Demo代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LoginDemo extends JFrame implements ActionListener {
private JLabel usernameLabel, passwordLabel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton, cancelButton;
public LoginDemo() {
super("Login Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null);
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password:");
usernameField = new JTextField(10);
passwordField = new JPasswordField(10);
loginButton = new JButton("Login");
cancelButton = new JButton("Cancel");
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
mainPanel.add(usernameLabel, c);
c.gridx = 1;
mainPanel.add(usernameField, c);
c.gridx = 0;
c.gridy = 1;
mainPanel.add(passwordLabel, c);
c.gridx = 1;
mainPanel.add(passwordField, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.anchor = GridBagConstraints.CENTER;
JPanel buttonPanel = new JPanel();
buttonPanel.add(loginButton);
buttonPanel.add(cancelButton);
mainPanel.add(buttonPanel, c);
add(mainPanel);
setVisible(true);
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (username.equals("admin") && password.equals("admin")) {
JOptionPane.showMessageDialog(null, "Login successful!");
dispose();
} else {
JOptionPane.showMessageDialog(null, "Invalid username or password!");
usernameField.setText("");
passwordField.setText("");
}
} else if (e.getSource() == cancelButton) {
dispose();
}
}
public static void main(String[] args) {
new LoginDemo();
}
}
```
该Demo使用了Swing库来创建和显示登录页面。其中,使用了GridBagLayout布局管理器来实现页面布局。登陆按钮和取消按钮分别添加了事件监听器,点击登陆按钮时根据输入的用户名和密码判断是否登录成功,登录成功则弹出提示框,否则清空输入框。点击取消按钮则关闭窗口。