LoginGUI.java

news2024/11/26 17:50:24

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.

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

TCP三次握手的过程

一、什么是TCP TCP是面向连接的、可靠的、基于字节流的传输层通信协议。 二、TCP的头部格式 序列号:在建立连接时由计算机生成的随机数作为其初始值,通过SYN包传给接收端主机,每发送一次数据,就「累加」一次该「数据字节数」的大小。用来解…

分数计算 初级题目

今天继续更题。今天的题目是《第五单元 分数的加减法》初级题目。 定位:题目较为初级,适合预习 参考答案:CACCADACAABACBBCDBCB

shell编程基础(第18篇:更多的文件操作命令介绍)

前言 对于文件来说,除了它的文件内容之外,就是对其文件本身的操作,比如我们想要重命名文件、移动文件、复制文件、已经获取文件所在目录,文件名等操作,今天一起学习更多的文件操作相关的命令 basename 用于获取文件名…

2024年【N2观光车和观光列车司机】考试技巧及N2观光车和观光列车司机模拟考试

题库来源:安全生产模拟考试一点通公众号小程序 N2观光车和观光列车司机考试技巧参考答案及N2观光车和观光列车司机考试试题解析是安全生产模拟考试一点通题库老师及N2观光车和观光列车司机操作证已考过的学员汇总,相对有效帮助N2观光车和观光列车司机模…

第12章.STM32标准库简介

目录 0. 《STM32单片机自学教程》专栏 12.1 CMSIS 标准 12.2 STM32标准库文件结构 12.2.1 主结构 12.2.2 Libraries固件库文件 CMSIS文件夹 1.core_cm3.c&core_cm3.h 2.startup启动文件 3.Stm32f10x.h 4.system_stm32f10x.c&system_stm32f10…

微前端乾坤方案

微前端乾坤方案 了解乾坤 官方文档 介绍 qiankun 是一个基于 single-spa 的微前端实现库,旨在帮助大家能更简单、无痛的构建一个生产可用微前端架构系统。 qiankun 的核心设计理念 🥄 简单 由于主应用微应用都能做到技术栈无关,qiankun 对…

乐鑫ESP32相关资料整理

乐鑫科技 Espressif 介绍 乐鑫科技 Espressif AIoT 领域软硬件产品的研发与设计,专注于研发高集成、低功耗、性能卓越、安全稳定、高性价比的无线通信 SoC,现已发布 ESP8266、ESP32、ESP32-S、ESP32-C 和 ESP32-H 系列芯片、模组和开发板。 Espressif Sy…

如何训练自己的大型语言模型?

简介 大型语言模型,如OpenAI的GPT-4或Google的PaLM,已经席卷了人工智能领域。然而,大多数公司目前没有能力训练这些模型,并且完全依赖于只有少数几家大型科技公司提供技术支持。 在Replit,我们投入了大量资源来建立从…

【Tkinter界面】Canvas 图形绘制(03/5)

文章目录 一、说明二、画布和画布对象2.1 画布坐标系2.2 鼠标点中画布位置2.3 画布对象显示的顺序2.4 指定画布对象 三、你应该知道的画布对象操作3.1 什么是Tag3.2 操作Tag的函数 https://www.cnblogs.com/rainbow-tan/p/14852553.html 一、说明 Canvas(画布&…

vue 安装依赖报错

解决方法: npm install --legacy-peer-deps 然后再运行项目即可。

springboot与flowable(9):候选人组

act_id_xxx相关表存储了所有用户和组的数据。 一、维护用户信息 Autowiredprivate IdentityService identityService;/*** 维护用户*/Testvoid createUser() {User user identityService.newUser("zhangsan");user.setEmail("zhangsanqq.com");user.setF…

探索互联网寻址机制 | 揭秘互联网技术的核心,解析网络寻址

揭秘互联网技术的核心,解析网络寻址题 前提介绍局域网地址IP地址的分配方式动态IP分配机制内部网(intranet)ICANN负责IP分配DHCP协议获取IP地址 域名系统域名是什么域名工作方式hosts文件存储域名映射关系DNS分布式数据库DNS域名解析 Java进行…

探索交互的本质:从指令到界面的演进与Linux基础指令的深入剖析

目录 1.指令 vs 界面//选读 1.1交互的需求 满足需求的第一阶段-指令 满足需求的第二阶段-界面 1.2 指令 和 界面交互 区别 2.操作系统介绍 2.1 举例说明 驱动软件层 2.2 为什么要有操作系统? 0x03 为什么要进行指令操作? 3.Linux基本指令 l…

数据防泄漏的六个步骤|数据防泄漏软件有哪些

在当前复杂多变的网络安全环境下,数据防泄漏软件成为了企业信息安全架构中不可或缺的一环。下面以安企神软件为例,告诉你怎么防止数据泄露,以及好用的防泄露软件。 1. 安企神软件 安企神软件是当前市场上备受推崇的企业级数据防泄漏解决方案…

关于反弹shell的学习

今天学习反弹shell,在最近做的ctf题里面越来越多的反弹shell的操作,所以觉得要好好研究一下,毕竟是一种比较常用的操作 什么是反弹shell以及原理 反弹Shell(也称为反向Shell)是一种技术,通常用于远程访问和…

ESP32 BLE学习(0) — 基础架构

前言 (1)学习本文之前,需要先了解一下蓝牙的基本概念:BLE学习笔记(0.0) —— 基础概念(0) (2) 学习一款芯片的蓝牙肯定需要先简单了解一下该芯片的体系结构&a…

模型 商业画布

说明:系列文章 分享 模型,了解更多👉 模型_思维模型目录。九块拼图,构建商业模式。 1 商业画布的应用 1.1 商业画布用于明确“GreenCycle”初创企业(虚构)的商业模式 假设有一家名为“GreenCycle”的初创…

实拆一个风扇

fr:徐海涛(hunkxu)

湖南源点调查 知识产权侵权案中企业如何品牌保护与收集证据

湖南源点调查认为,要判断某产品是否侵犯了自己的知识产权,可以采取以下步骤: 明确自己的知识产权: 首先,确保你的知识产权(如商标、专利、著作权等)已经获得合法的注册或保护。 仔细研究你的…

IO流及字符集

IO流 作用: 用于读写文件中的数据 分类: 图来自黑马程序员网课 纯文本文件:Windows自带的记事本打开能读懂的文件,word excel不是纯文本文件 图来自黑马程序员网课 FileOutputStream: 操作本地文件的字节输出流,可…