使用JFrame创建登录窗口(可参考下图或自行设计布局) 当点击登录按钮时,对输入的用户名为和密码进行验证: 当输入的用户为admin,密码为1234时,弹出消息对话框,提示信息为:“用户名和密码正确”,否则,提
时间: 2024-03-17 21:40:59 浏览: 153
创建JFrame窗口-java图形示例
示错误消息对话框,提示信息为:“用户名或密码错误”。以下是 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;
private JButton loginButton;
public LoginFrame() {
setTitle("Login");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
JLabel usernameLabel = new JLabel("Username:");
panel.add(usernameLabel);
usernameField = new JTextField();
panel.add(usernameField);
JLabel passwordLabel = new JLabel("Password:");
panel.add(passwordLabel);
passwordField = new JPasswordField();
panel.add(passwordField);
loginButton = new JButton("Login");
loginButton.addActionListener(this);
panel.add(loginButton);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (username.equals("admin") && password.equals("1234")) {
JOptionPane.showMessageDialog(this, "Username and password are correct.");
} else {
JOptionPane.showMessageDialog(this, "Username or password is incorrect.");
}
}
public static void main(String[] args) {
LoginFrame loginFrame = new LoginFrame();
}
}
```
这段代码创建了一个登录窗口,包含用户名输入框、密码输入框和登录按钮。当用户点击登录按钮时,程序会读取输入框中的用户名和密码,并判断是否正确。如果用户名为 "admin" 且密码为 "1234",则弹出提示框显示"Username and password are correct.",否则弹出提示框显示"Username or password is incorrect."。
阅读全文