LoginGUI.java

作者 : admin 本文共9052个字,预计阅读时间需要23分钟 发布时间: 2024-06-16 共1人阅读

LoginGUI.java

完成效果如下图:

LoginGUI.java插图

CODE

Summary:

This code sets up a login GUI using Swing.

It defines a LoginGUI class extending JFrame.

The constructor initializes the GUI components and sets up event listeners.

The event_login method handles the login logic, displaying messages based on the success or failure of the login attempt.

/*
package com.shiyanlou.view; - This declares the package name.
The import statements import various classes needed for the GUI components and event handling from the javax.swing and java.awt libraries, as well as a custom utility class JDOM.
*/
package com.shiyanlou.view;
​
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
​
import com.shiyanlou.util.JDOM;
​
/Class Declaration
/*
LoginGUI extends JFrame, which means it is a type of window.
--
serialVersionUID is a unique identifier for the class, used during deserialization.
--
contentPane is a JPanel that acts as the main panel of the frame.
--
IDtxt, Passwdlabel, and passwordField are components for user input and labels.
--
login and back are buttons for submitting the login form and going back to the main window.
*/
public class LoginGUI extends JFrame {
    private static final long serialVersionUID = 4994949944841194839L;
    private JPanel contentPane; //面板
    private JTextField IDtxt; //ID输入框
    private JLabel Passwdlabel; //密码标签
    private JPasswordField passwordField; //密码输入框
    private JButton login;//登录按钮
    private JButton back;//返回按钮
    
/  Member Method: loginGUI
/*
This method starts the application by creating and displaying the LoginGUI frame in the Event Dispatch Thread, ensuring thread safety.
*/
 /*
 
 */
 
/**
 * Launch the application.
 * @return
 */
public void loginGUI() {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                LoginGUI frame = new LoginGUI();
                frame.setVisible(true);
                
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    });
}
    
Constructor: LoginGUI
/*
The constructor initializes the frame, sets the default close operation, size, and layout.
--
contentPane is set up as the main panel with a border and null layout for absolute positioning.
--
Labels and text fields (IDlabel, IDtxt, Passwdlabel, passwordField) are created and added to contentPane.
--
The login button is created, with mouse and key event listeners attached to handle clicks and Enter key presses.
--
The back button is created, with a mouse event listener to return to the main window.
A welcome label is added to the frame.
*/
    
//构造方法
/**
 * Create the frame.
 */
public LoginGUI() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    setBounds(100,100,650,400);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5,5,5,5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    
    JLabel IDlabel = new JLabel("Please input ID");//id 标签
    IDlabel.setBounds(68,170,100,39);
    contentPane.add(IDlabel);
    
    IDtxt = new JTextField();
    IDtxt.setBounds(220, 179, 126, 21);
    contentPane.add(IDtxt);
    IDtxt.setColumns(10);
    
    Passwdlabel = new JLabel("Please input password");
    Passwdlabel.setBounds(68, 219, 150, 50);
    contentPane.add(Passwdlabel);
    
    passwordField = new JPasswordField();
    passwordField.setBounds(220, 234, 126, 21);
    contentPane.add(passwordField);
    
    login = new JButton("login");
    
    //鼠标事件
    login.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            event_login();//登录事件方法
        }
    });
    
    //键盘事件
    login.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER) {//当键盘按enter时调用
                event_login();//登录事件方
                
            }
        }
    });
    login.setBounds(239, 310, 93, 23);
    contentPane.add(login);
    
    //返回按钮
    back = new JButton("BACK");
    back.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            IndexGUI.init();
            setVisible(false);
        }
    });
    back.setBounds(507, 310, 93, 23);
    contentPane.add(back);
    
     //标题
    JLabel label  = new JLabel("Welcome to use KnowYou");
    label.setFont(new Font("Ubuntu",Font.BOLD | Font.ITALIC,30));
    
}
   
/event_login
/*
This method handles the login logic when the login button is clicked or Enter is pressed.
--
It retrieves the user ID and password from the input fields.
--
It calls JDOM.read(id, passwd) to validate the credentials.
--
If the login is successful, it displays a welcome message and opens the user GUI (UsersGUI.init(name)).
--
If the login fails, it shows an error message.
*/
    //封装登录事件
private void event_login() {
     //这里的登录事件方法暂不处理,日后补充。
    String id = IDtxt.getText();
    String passwd = new String(passwordField.getPassword());
    String flag = JDOM.read(id, passwd);
    
    if(flag.contains("Successful landing")) {
        //拆分信息
        String[] bufs = flag.split("/");
        String name = bufs[1];
        //提示框,打印登录成功
        JOptionPane.showMessageDialog(contentPane, "Welcome: "+name,"Welcome", JOptionPane.PLAIN_MESSAGE);
        UsersGUI.init(name);
        setVisible(false);
    }
    else {
        //提示框,错误信息
        JOptionPane.showMessageDialog(contentPane, flag,"ERROR",JOptionPane.ERROR_MESSAGE);
    }
}
}

tips:

understanding the details of the code is crucial for a Java developer. Knowing the specifics allows you to:

  1. debug effectively

  2. write better code

  3. understand others’ code

  4. optimize performance

  5. implement features

Event Dispatch Thread

javaCopy codeEventQueue.invokeLater(new Runnable() {
    public void run() {
        try {
            LoginGUI frame = new LoginGUI();
            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
  • Purpose: Ensures that the creation and updating of GUI components happen on the Event Dispatch Thread (EDT), which is the thread responsible for handling GUI events in Swing.

  • Details

    :

    • EventQueue.invokeLater(Runnable runnable): Schedules the specified Runnable to be executed on the EDT.

    • new Runnable() { public void run() { ... } }: Defines the Runnable‘s run method, which is executed on the EDT.

    • LoginGUI frame = new LoginGUI();: Creates an instance of LoginGUI.

    • frame.setVisible(true);: Makes the frame visible.

Constructor: LoginGUI

javaCopy codesetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
  • Purpose: Sets up the main window and its content pane.

  • Details

    :

    • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);: Specifies that the application should exit when the window is closed.

    • setBounds(int x, int y, int width, int height);: Sets the position and size of the frame.

    • contentPane = new JPanel();: Initializes contentPane.

    • contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));: Adds an empty border with 5-pixel padding around the contentPane.

    • setContentPane(contentPane);: Sets contentPane as the content pane for the frame.

    • contentPane.setLayout(null);: Uses absolute positioning for the layout of contentPane.

Adding Components

javaCopy codeJLabel IDlabel = new JLabel("Please input ID");
IDlabel.setBounds(68, 170, 100, 39);
contentPane.add(IDlabel);
​
IDtxt = new JTextField();
IDtxt.setBounds(220, 179, 126, 21);
contentPane.add(IDtxt);
IDtxt.setColumns(10);
  • Purpose: Adds a label and a text field for user ID input.

  • Details

    :

    • JLabel IDlabel = new JLabel("Please input ID");: Creates a label with the specified text.

    • IDlabel.setBounds(int x, int y, int width, int height);: Sets the position and size of the label.

    • contentPane.add(IDlabel);: Adds the label to contentPane.

    • IDtxt = new JTextField();: Creates a text field for user input.

    • IDtxt.setBounds(int x, int y, int width, int height);: Sets the position and size of the text field.

    • contentPane.add(IDtxt);: Adds the text field to contentPane.

    • IDtxt.setColumns(int columns);: Sets the number of columns in the text field, affecting its preferred width.

Event Listeners

javaCopy codelogin.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        event_login();
    }
});
​
login.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            event_login();
        }
    }
});
  • Purpose: Attaches event listeners to the login button for handling mouse clicks and key presses.

  • Details

    :

    • login.addMouseListener(new MouseAdapter() { ... });: Adds a mouse listener to handle mouse events.

    • mouseClicked(MouseEvent e): Called when the login button is clicked.

    • event_login();: Calls the event_login method to handle the login process.

    • login.addKeyListener(new KeyAdapter() { ... });: Adds a key listener to handle key events.

    • keyPressed(KeyEvent e): Called when a key is pressed while the login button is focused.

    • if (e.getKeyCode() == KeyEvent.VK_ENTER) { ... }: Checks if the Enter key was pressed.

Event Handling Method: event_login

javaCopy codeprivate void event_login() {
    String id = IDtxt.getText();
    String passwd = new String(passwordField.getPassword());
    String flag = JDOM.read(id, passwd);
    
    if (flag.contains("Successful landing")) {
        String[] bufs = flag.split("/");
        String name = bufs[1];
        JOptionPane.showMessageDialog(contentPane, "Welcome: " + name, "Welcome", JOptionPane.PLAIN_MESSAGE);
        UsersGUI.init(name);
        setVisible(false);
    } else {
        JOptionPane.showMessageDialog(contentPane, flag, "ERROR", JOptionPane.ERROR_MESSAGE);
    }
}
  • Purpose: Handles the login process by validating user credentials.

  • Details

    :

    • String id = IDtxt.getText();: Retrieves the user ID from the text field.

    • String passwd = new String(passwordField.getPassword());: Retrieves the password from the password field.

    • String flag = JDOM.read(id, passwd);: Calls a method from JDOM to validate the credentials and returns a result string.

    • if (flag.contains("Successful landing")) { ... }: Checks if the login was successful.

    • String[] bufs = flag.split("/");: Splits the result string to extract the user’s name.

    • String name = bufs[1];: Gets the user’s name.

    • JOptionPane.showMessageDialog(contentPane, "Welcome: " + name, "Welcome", JOptionPane.PLAIN_MESSAGE);: Displays a welcome message.

    • UsersGUI.init(name);: Initializes the user GUI with the user’s name.

    • setVisible(false);: Hides the login window.

    • else { ... }: Displays an error message if the login failed.

本站无任何商业行为
个人在线分享 » LoginGUI.java
E-->