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.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/724668.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【DAMA】掌握数据管理核心:CDGA考试指南

引言:        在当今快速发展的数字化世界中,数据已成为组织最宝贵的资产之一。有效的数据管理不仅能够驱动业务决策,还能提升竞争力和市场适应性。DAMA国际一直致力于数据管理和数字化的研究、实践及相关知识体系的建设。秉承公益、志愿…

2024年一建要通关,这300道题必刷!

​一级建造师备考的过程,就是不断地消灭错题的过程! 考试100教研团队为大家编写了一套《2024年一级建造师易考易错300题》。考前冲刺期错题集就是你涨粉的法宝,将错题原因反复检测,真正掌握好错题点和题型解题核心得分要点才是提分关键! 明确…

最好用的智能猫砂盆存在吗?自用分享智能猫砂盆测评!

在现代都市的忙碌生活中,作为一名上班族,经常因为需要加班或频繁出差而忙碌得不可开交。急匆匆地出门,却忘了给猫咪及时铲屎。但是大家要知道,不及时清理猫砂盆会让猫咪感到不适,还会引发各种健康问题,如泌…

程序员失业了,你可以做这些事情

这篇文章,我们讲,你先别带入自己哈,如果失业了,放心吧,你那么有上进心,不会失业的。咱就是说,如果万一失业了,你可以做这些事情。 1 体力好的铁人三项 👩‍&#x1f3e…

集合进阶:List集合

一.List集合的特有方法 1.Collection的方法List都继承了 2.List集合因为有索引,所以多了很多索引操作的方法。 3.add // 1.创建一个集合List<String> list new ArrayList<>(); // 2.添加元素list.add("aaa");list.add("bbb"…

mac禁用电池睡眠-mac盒盖连接显示器

mac禁用电池睡眠-mac盒盖连接显示器-mac断点盒盖连接显示器 讲解&#xff1a;mac盒盖的时候连接显示器会睡眠并断开和显示器的连接&#xff0c;只有在电池->选项->选择使用电源适配器的时候防止睡眠&#xff0c;才可以连接电源线外界显示器 但是苹果的电池相当于手机电…

[Vulnhub] BrainPan BOF缓冲区溢出+Man权限提升

信息收集 Server IP AddressPorts Open192.168.8.105TCP: $ nmap -p- 192.168.8.105 -sC -sV -Pn --min-rate 1000 Starting Nmap 7.92 ( https://nmap.org ) at 2024-06-10 04:20 EDT Nmap scan report for 192.168.8.105 (192.168.8.105) Host is up (0.0045s latency). N…

easyexcel和poi版本冲突报错深入解析v2

easyexcel报错解决 问题 项目由poi改用easyexcel&#xff0c;报错如下&#xff1a; java.lang.NoSuchMethodError: ‘org.apache.poi.ss.usermodel.CellType org.apache.poi.ss.usermodel.Cell.getCellType()’ 原因 easyexcel中的poi和项目原本的poi版本冲突问题。 由于之前做…

npm install 安装不成功,node-sass缺失,提示python环境缺失的解决办法

npm install 安装不成功的原因 是因为缺少python的环境 解决方法&#xff1a; 1、去官网下载 https://www.python.org/downloads/release&#xff0c;注意安装3.6版本以上还是会有问题&#xff0c;建议安装3.6版本以上的&#xff0c;我选择安装的是3.9.6&#xff0c;对应的下载…

操作系统 大作业

1、现有成绩文件按“姓名 学校 年级 班级 分数”五列组成&#xff0c;编写Shell脚本&#xff0c;将某目录下所有成绩文件&#xff08;≥3个&#xff09;合并为一个&#xff0c;形成“姓名 班级 分数”三列&#xff0c;并按成绩排序&#xff0c;输出年级排名前十。同时输出60以下…

移植案例与原理 - HDF驱动框架-驱动配置(1)

HCS(HDF Configuration Source)是HDF驱动框架的配置描述源码&#xff0c;内容以Key-Value为主要形式。它实现了配置代码与驱动代码解耦&#xff0c;便于开发者进行配置管理。应该&#xff0c;类似Linux DTS(Device Tree Source)设备树。 HC-GEN(HDF Configuration Generator)是…

质检迈入新时代,天润融通推出基于大模型的质检3.0解决方案

近18个月以来&#xff0c;受益于生成式AI浪潮&#xff0c;千行百业迎来了前所未有的突破与变革。 今天我们荣幸地站在时代交汇点上&#xff0c;宣布天润融通正式推出基于大语言模型的质检3.0产品&#xff0c;文末扫码申请试用。 在揭示质检3.0的里程碑之前&#xff0c;让我们…

网工内推 | 中国电信、香港宽频系统工程师,CCIE认证优先,最高年薪25w

01 中国电信股份有限公司浙江分公司 &#x1f537;招聘岗位&#xff1a;系统架构师 &#x1f537;岗位职责&#xff1a; 1、做好客户网络和信息安全产品的解决方案支撑、交付及后续运营维护&#xff0c;做好相关产数项目的支撑。 2、根据信息安全管理要求&#xff0c;负责客户…

MPLS静态配置实验(初学版)

实验拓扑 配置接口地址 配置OSPF协议 测试网络连通性 配置静态MPLS AR1&#xff1a; [R1]mpls lsr-id 1.1.1.1 [R1]mpls [R1-GigabitEthernet0/0/0]mpls [R1]static-lsp ingress wps destination 4.4.4.4 32 nexthop 10.1.12.2 outgoing-interface g0/0/0 out-label 100AR2 [R2…

韩顺平0基础学java——第26天

p523-547 HashSet扩容时&#xff0c;只要节点到达了阈值就会扩&#xff0c;而不是数组长度到了才扩。 比如长16的数组&#xff0c;索引1放了8个&#xff0c;索引3放了4个&#xff0c;我再加一个他就会扩容。 另外谁能告诉我老师的debug界面是怎么设置的吗忘光了 HashSet存放…

shell脚本之数组及冒泡排序

1.数组定义&#xff1a;在集合当中指定多个元素&#xff0c;元素的类型可以是整数、字符串及浮点。 2.数组作用&#xff1a;一次性的定义多个元素&#xff0c;可以为变量赋值提供便利。 3.数组的定义方法&#xff1a; 数组名&#xff08;a b c d&#xff09; 数组名不能重复…

Qt6视频播放器项目框架代码

视频播放的关键代码如下: 使用Qt6的QMediaPlayer,QVideoWidget实现 void FunnyWidget::initVideo() {player = new QMediaPlayer(this);videoWidget = new QVideoWidget(this);playButton = new QPushButton("Play", this);pauseButton = new QPushButton("…

【Ruby基础01】windows和termux中搭建Ruby开发环境

windows下环境搭建 railsinstaller官方git地址 按照文档安装git、nodejs、yarn&#xff0c;安装教程百度一下。railsinstall可以从release页面下载最新版本4.1.0。 安装完成如下 安装RubyMine 下载RubyMine RubyMine下载地址 安装激活 下载文件&#xff0c;按照里面的流程…

《算法设计与分析》第五六章:回溯法与分支限界法

文章目录 回溯法分支限界法一、本章作业1.活动安排问题2.旅行商问题3.单源最短路径4.任务分配问题 二、算法积累1.回溯法求解01背包问题2.回溯法求解最大团问题3.回溯法求解n皇后问题4.回溯法求解地图着色5.回溯法求解哈密尔顿图6.回溯法求活动安排7.分支限界法求01背包问题8.分…

手写MyBatis 重要基本原理框架

1. 手写MyBatis 重要基本原理框架 文章目录 1. 手写MyBatis 重要基本原理框架1.1 第一步&#xff1a;IDEA中创建模块1.2 第二步&#xff1a;资源工具类&#xff0c;方便获取指向配置文件的输入流1.3 第三步&#xff1a;定义SqlSessionFactoryBuilder类1.4 第四步&#xff1a;分…