用Java写一个登录界面
时间: 2024-03-17 08:45:44 浏览: 14
好的,以下是一个简单的Java登录界面示例:
```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);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
userLabel = new JLabel("用户名:");
passwordLabel = new JLabel("密码:");
userTextField = new JTextField();
passwordField = new JPasswordField();
loginButton = new JButton("登录");
loginButton.addActionListener(this);
add(userLabel);
add(userTextField);
add(passwordLabel);
add(passwordField);
add(new JLabel());
add(loginButton);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String username = userTextField.getText();
String password = String.valueOf(passwordField.getPassword());
if (username.equals("admin") && password.equals("123456")) {
JOptionPane.showMessageDialog(this, "登录成功!");
dispose();
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
这个例子使用了Java Swing框架来创建登录界面,其中包括用户名和密码输入框、登录按钮,并通过JOptionPane显示登录结果。当用户点击登录按钮时,程序会检查用户名和密码是否匹配,并弹出相应的提示框。