java完成登陆界面的设计,并能点击✕关闭窗口。输入用户名和密码后点击OK如果和你设计的用户名和密码相同则在最上面的文本行中显示登陆成功,否则显示登陆失败。点击Cancel,则把文本行置空。
时间: 2023-12-14 11:40:07 浏览: 36
以下是一个简单的Java登陆界面设计代码,可以实现上述功能:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
private JLabel userLabel, passwordLabel, infoLabel;
private JTextField userText;
private JPasswordField passwordText;
private JButton okButton, cancelButton;
public LoginFrame() {
setTitle("Login");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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");
infoLabel = new JLabel();
add(userLabel);
add(userText);
add(passwordLabel);
add(passwordText);
add(okButton);
add(cancelButton);
okButton.addActionListener(this);
cancelButton.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == okButton) {
String username = userText.getText();
String password = new String(passwordText.getPassword());
if (username.equals("admin") && password.equals("password")) {
infoLabel.setText("Login success!");
} else {
infoLabel.setText("Login failed!");
}
} else if (event.getSource() == cancelButton) {
userText.setText("");
passwordText.setText("");
infoLabel.setText("");
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
在上面的代码中,我们创建了一个继承自JFrame的LoginFrame类。在构造函数中,我们设置了窗口的标题、大小、默认关闭操作、位置和布局,并创建了用户名、密码、OK和Cancel按钮以及信息标签。
在ActionListener中,我们分别处理了点击OK和Cancel两个按钮的事件。当点击OK按钮时,我们获取到用户输入的用户名和密码,并与预设的用户名和密码进行比较。如果相同,则在信息标签中显示“Login success!”,否则显示“Login failed!”。当点击Cancel按钮时,我们将用户名、密码和信息标签都置空。
最后,我们在main方法中创建了一个LoginFrame对象,即可实现登陆界面的显示。