用JAVAGUI设计用户界面,若用户名称为“www”,用户密码为“888”,单击登录时控制台显示登录成功,否则显示登录失败,单击取消退出应用程序。
时间: 2023-12-31 18:03:45 浏览: 29
以下是一个简单的Java GUI示例代码,实现您所需的功能:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginGUI extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
public LoginGUI() {
setTitle("用户登录");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(3, 2));
JLabel usernameLabel = new JLabel("用户名:");
usernameField = new JTextField();
contentPane.add(usernameLabel);
contentPane.add(usernameField);
JLabel passwordLabel = new JLabel("密 码:");
passwordField = new JPasswordField();
contentPane.add(passwordLabel);
contentPane.add(passwordField);
JButton loginButton = new JButton("登录");
loginButton.addActionListener(this);
contentPane.add(loginButton);
JButton cancelButton = new JButton("取消");
cancelButton.addActionListener(this);
contentPane.add(cancelButton);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("登录")) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (username.equals("www") && password.equals("888")) {
JOptionPane.showMessageDialog(this, "登录成功");
} else {
JOptionPane.showMessageDialog(this, "登录失败");
}
} else if (event.getActionCommand().equals("取消")) {
System.exit(0);
}
}
public static void main(String[] args) {
new LoginGUI();
}
}
```
该程序中,`JFrame`是一个顶层的窗口容器,`JLabel`是一个简单的文本标签,`JTextField`是一个单行的文本输入框,`JPasswordField`是一个密码输入框,`JButton`是一个按钮。`JOptionPane`是一个弹出式对话框,用于显示登录结果。
在`actionPerformed()`方法中,根据按钮的不同响应进行相应的操作。如果单击登录按钮,则获取用户名和密码,判断是否等于“www”和“888”,如果是则弹出登录成功的提示框,否则弹出登录失败的提示框。如果单击取消按钮,则退出程序。