编辑代码

import javax.swing.*;  
import java.awt.*;  
import java.awt.event.*;  
  
public class UserLoginRegister extends JFrame implements ActionListener {  
    private JLabel userLabel, passwordLabel;  
    private JTextField userTextField;  
    private JPasswordField passwordField;  
    private JButton loginButton, registerButton;  
  
    public UserLoginRegister() {  
        // 设置窗口标题  
        setTitle("用户登录注册");  
  
        // 创建组件  
        userLabel = new JLabel("用户名:");  
        passwordLabel = new JLabel("密码:");  
        userTextField = new JTextField();  
        passwordField = new JPasswordField();  
        loginButton = new JButton("登录");  
        registerButton = new JButton("注册");  
  
        // 设置布局  
        setLayout(new GridLayout(3, 2));  
  
        // 添加组件到窗口中  
        add(userLabel);  
        add(userTextField);  
        add(passwordLabel);  
        add(passwordField);  
        add(loginButton);  
        add(registerButton);  
  
        // 设置组件大小和位置  
        setSize(300, 150);  
        setLocationRelativeTo(null);  
  
        // 添加事件监听器  
        loginButton.addActionListener(this);  
        registerButton.addActionListener(this);  
    }  
  
    public void actionPerformed(ActionEvent e) {  
        if (e.getSource() == loginButton) {  
            // 获取用户名和密码并验证是否正确,这里只是简单地输出到控制台,实际应用中需要进行验证和安全处理。  
            String username = userTextField.getText();  
            String password = new String(passwordField.getPassword());  
            System.out.println("用户名:" + username + ",密码:" + password);  
        } else if (e.getSource() == registerButton) {  
            // 打开注册窗口,这里只是一个简单的对话框,实际应用中需要添加更复杂的注册功能。  
            JOptionPane.showMessageDialog(this, "请输入用户名和密码进行注册。");  
        } else {  
            System.out.println("未知操作");  
        }  
    }  
  
    public static void main(String[] args) {  
        UserLoginRegister app = new UserLoginRegister();  
        app.setVisible(true);  
    }  
}