用Java完成登陆界面的设计,并能点击✕关闭窗口。输入用户名和密码后点击OK如果和你设计的用户名和密码相同则在最上面的文本行中显示登陆成功,否则显示登陆失败。点击Cancel,则把文本行置空。
时间: 2023-06-26 22:07:46 浏览: 80
以下是Java代码实现:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame implements ActionListener {
private JLabel userLabel, passwordLabel;
private JTextField userText, passwordText;
private JButton okButton, cancelButton;
private JTextArea resultArea;
public LoginFrame() {
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
setLayout(new GridLayout(3, 2));
userLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password:");
userText = new JTextField();
passwordText = new JPasswordField();
okButton = new JButton("OK");
cancelButton = new JButton("Cancel");
resultArea = new JTextArea();
add(userLabel);
add(userText);
add(passwordLabel);
add(passwordText);
add(okButton);
add(cancelButton);
okButton.addActionListener(this);
cancelButton.addActionListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == okButton) {
String username = userText.getText();
String password = passwordText.getText();
if (username.equals("admin") && password.equals("admin")) {
resultArea.setText("Login successful.");
} else {
resultArea.setText("Login failed.");
}
} else if (e.getSource() == cancelButton) {
resultArea.setText("");
userText.setText("");
passwordText.setText("");
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
这个程序使用了Java的Swing GUI库来实现界面。在构造函数中创建了用户名、密码输入框、OK和Cancel按钮以及结果文本框。然后为OK和Cancel按钮添加了ActionListener,当用户点击按钮时会调用actionPerformed方法。在这个方法中判断用户输入的用户名和密码是否正确,如果正确则在结果文本框中显示“Login successful.”,否则显示“Login failed.”。在点击Cancel按钮时,清空所有输入框和结果文本框。