java简单的用户登录界面+mysql

Wesley13
• 阅读 479

1.概述

一个简单的swing登录界面,使用了简单的JDBC. 如图:

java简单的用户登录界面+mysql

java简单的用户登录界面+mysql

2.UI

(1)主界面

主界面使用了3_1网格布局+三个JPanel,中间的JPanel使用了2_2网格布局:

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Enumeration;
import java.awt.Container;

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.UIManager;
import javax.swing.plaf.FontUIResource;

public class UserManagement
{
    private JFrame mainFrame = new JFrame("登录");
    private Container container = mainFrame.getContentPane();
    private JLabel titleLabel = new JLabel("登录/注册", JLabel.CENTER);

    private JPanel inputField = new JPanel();
    private JLabel usernameLabel = new JLabel("用户名:", JLabel.CENTER);
    private JTextField username = new JTextField();
    private JLabel passwordLabel = new JLabel("密码:", JLabel.CENTER);
    private JPasswordField password = new JPasswordField();

    private JPanel buttonField = new JPanel();
    private JButton save = new JButton("登录/注册");
    private JButton cancel = new JButton("取消");

    public UserManagement()
    {
        init();
        setFont(new Font("微软雅黑",Font.PLAIN,14));
        addEvent();
    }

    private void init()
    {
        container.setLayout(new GridLayout(3, 1, 0, 10));
        container.add(titleLabel);

        inputField.setLayout(new GridLayout(2, 2, 5, 5));
        inputField.add(usernameLabel);
        inputField.add(username);
        inputField.add(passwordLabel);
        inputField.add(password);
        container.add(inputField);

        buttonField.setLayout(new FlowLayout(FlowLayout.CENTER,20,0));
        buttonField.add(save);
        buttonField.add(cancel);
        container.add(buttonField);

        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(300, 200);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
    }

    private void setFont(Font font)
    {
        FontUIResource fontRes = new FontUIResource(font);
        for(Enumeration<Object> keys = UIManager.getDefaults().keys();keys.hasMoreElements();)
        {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if(value instanceof FontUIResource)
                UIManager.put(key, fontRes);
        }
    }

    private void addEvent()
    {
        save.addActionListener(
            e->
            {
                User user = new User();
                user.setName(username.getText());
                user.setPassword(new String(password.getPassword()));
                if(DBUtils.exists(user))
                    new UserInformation(DBUtils.getByName(user.getName()));
                else
                    JOptionPane.showConfirmDialog(null,
                    "添加"+(DBUtils.add(user) ? "成功" : "失败"), "",JOptionPane.CLOSED_OPTION);
            }
        );

        cancel.addActionListener(
            e->
            {
                mainFrame.dispose();
            }
        );
    }

    public static void main(String[] args)
    {
        new UserManagement();
    }
}

重点说一下几行代码:

mainFrame.setLocationRelativeTo(null);

使整个JFrame处于屏幕水平居中与垂直居中位置.

private void setFont(Font font)
{
    FontUIResource fontRes = new FontUIResource(font);
    for(Enumeration<Object> keys = UIManager.getDefaults().keys();keys.hasMoreElements();)
    {
        Object key = keys.nextElement();
        Object value = UIManager.get(key);
        if(value instanceof FontUIResource)
            UIManager.put(key, fontRes);
    }
}

设置所有组件的字体.

cancel.addActionListener(
  e->
    {
        mainFrame.dispose();
    }
);

按钮添加关闭窗口事件.

JOptionPane.showConfirmDialog(null,"添加"+(DBUtils.add(user) ? "成功" : "失败"), "",JOptionPane.CLOSED_OPTION);

提示信息框.

(2)用户信息界面

用户信息界面采用了3_1网格,同样3个JPanel,中间的JPanel布局为3_2网格.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Enumeration;
import java.awt.Container;

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.UIManager;
import javax.swing.plaf.FontUIResource;

public class UserInformation
{
    private JFrame mainFrame = new JFrame("用户信息");
    private Container container = mainFrame.getContentPane();
    private JLabel titleLabel = new JLabel("用户信息", JLabel.CENTER);

    private JPanel inputField = new JPanel();
    private JLabel idLabel = new JLabel("Id",JLabel.CENTER);
    private JTextField id = new JTextField();
    private JLabel usernameLabel = new JLabel("Username", JLabel.CENTER);
    private JTextField username = new JTextField();
    private JLabel passwordLabel = new JLabel("Password", JLabel.CENTER);
    private JPasswordField password = new JPasswordField();

    private JPanel buttonField = new JPanel();
    private JButton update = new JButton("更新");
    private User user;

    public UserInformation(User user)
    {
        if(user == null)
            mainFrame.dispose();
        this.user = user;
        init();
        setFont(new Font("微软雅黑", Font.PLAIN, 14));
        addEvent();
    }

    private void init()
    {
        container.setLayout(new GridLayout(3,1,0,10));
        container.add(titleLabel);

        inputField.setLayout(new GridLayout(3,2,0,3));
        inputField.add(idLabel);
        inputField.add(id);
        id.setText(user.getId());
        id.setEditable(false);
        inputField.add(usernameLabel);
        username.setText(user.getName());
        inputField.add(username);
        inputField.add(passwordLabel);
        password.setText(user.getPassword());
        inputField.add(password);
        container.add(inputField);

        buttonField.setLayout(new FlowLayout());
        buttonField.add(update);
        container.add(buttonField);

        mainFrame.setVisible(true);
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setSize(300,250);
    }

    private void setFont(Font font)
    {
        FontUIResource fontRes = new FontUIResource(font);
        for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();)
        {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource)
                UIManager.put(key, fontRes);
        }
    }

    private void addEvent()
    {
        update.addActionListener(
            e->
            {
                user.setName(username.getText());
                user.setPassword(new String(password.getPassword()));
                JOptionPane.showConfirmDialog(null, "更新"+(DBUtils.modify(user) ? "成功" : "失败"),"确认",JOptionPane.CLOSED_OPTION);
            }
        );
    }
}

这个JFrame不能设置EXIT_ON_CLOSE.因为这不是"主窗体",不然的话点击关闭主窗体也没了.

mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

3.数据库操作

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

public class DBUtils
{
    private final static String driver = "com.mysql.cj.jdbc.Driver";
    private final static String username = "aa";
    private final static String password = "123456";
    private final static String url = "jdbc:mysql://127.0.0.1/user_test";
    private final static String insert = "insert into user(id,username,password) values(?,?,?)";
    private final static String update = "update user set username = ?,password = ? where id = ?";
    private final static String delete = "delete from user where id = ?";
    private final static String select = "select * from user where username = ?";

    private static Connection connection;

    static
    {
        try
        {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,username,password);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            connection = null;
        }
    }

    public static boolean exists(User user)
    {
        try
        {
            PreparedStatement exist = connection.prepareStatement(select);
            exist.setString(1,user.getName());
            ResultSet existResult = exist.executeQuery();
            return existResult.next();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean add(User user)
    {
        try
        {
            PreparedStatement add = connection.prepareStatement(insert);
            user.setId(UUID.randomUUID().toString().substring(0, 8));
            add.setString(1, user.getId());
            add.setString(2, user.getName());
            add.setString(3, user.getPassword());
            return add.executeUpdate() == 1;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean modify(User user)
    {
        try
        {
            PreparedStatement modify = connection.prepareStatement(update);
            System.out.println(user.getName());
            modify.setString(1, user.getName());
            modify.setString(2, user.getPassword());
            modify.setString(3, user.getId());
            return modify.executeUpdate() == 1;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean delete(User user)
    {
        if(exists(user))
        {
            try
            {
                PreparedStatement del = connection.prepareStatement(delete);
                del.setString(1, user.getId());
                return del.executeUpdate() == 1;
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static User getByName(String name)
    {
        try
        {
            PreparedStatement exist = connection.prepareStatement(select);
            exist.setString(1, name);
            ResultSet existResult = exist.executeQuery();
            if(existResult.next())
            {
                User user = new User();
                user.setId(existResult.getString("id"));
                user.setName(existResult.getString("username"));
                user.setPassword(existResult.getString("password"));
                return user;
            }
            return null;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return null;
        }
    }
}

注册驱动后,增删查改,就是注意一下mysql版本与驱动名对应.

4.完整代码

github

码云

点赞
收藏
评论区
推荐文章
秃头王路飞 秃头王路飞
2个月前
webpack5手撸vue2脚手架
webpack5手撸vue相信工作个12年的小伙伴们在面试的时候多多少少怕被问到关于webpack方面的知识,本菜鸟最近闲来无事,就尝试了手撸了下vue2的脚手架,第一次发帖实在是没有经验,望海涵。 language JavaScript "name": "vuecliversion2", "version": "1.0.0", "desc
技术小男生 技术小男生
2个月前
linux环境jdk环境变量配置
1:编辑系统配置文件vi /etc/profile2:按字母键i进入编辑模式,在最底部添加内容: JAVAHOME/opt/jdk1.8.0152 CLASSPATH.:$JAVAHOME/lib/dt.jar:$JAVAHOME/lib/tools.jar PATH$JAVAHOME/bin:$PATH3:生效配置
光头强的博客 光头强的博客
2个月前
Java面向对象试题
1、 请创建一个Animal动物类,要求有方法eat()方法,方法输出一条语句“吃东西”。 创建一个接口A,接口里有一个抽象方法fly()。创建一个Bird类继承Animal类并实现 接口A里的方法输出一条有语句“鸟儿飞翔”,重写eat()方法输出一条语句“鸟儿 吃虫”。在Test类中向上转型创建b对象,调用eat方法。然后向下转型调用eat()方
blmius blmius
1年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录 问题 用navicat导入数据时,报错: 原因这是因为当前的MySQL不支持datetime为0的情况。 解决修改sql\mode: sql\mode:SQL Mode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。 全局s
小森森 小森森
2个月前
校园表白墙微信小程序V1.0 SayLove -基于微信云开发-一键快速搭建,开箱即用
后续会继续更新,敬请期待2.0全新版本 欢迎添加左边的微信一起探讨!项目地址:](https://www.aliyun.com/activity/daily/bestoffer?userCodesskuuw5n) \2. Bug修复更新日历 2. 情侣脸功能大家不要使用了,现在阿里云的接口已经要收费了(土豪请随意), \ \ 和 注意
Wesley13 Wesley13
1年前
Java爬虫之JSoup使用教程
title: Java爬虫之JSoup使用教程 date: 2018-12-24 8:00:00 +0800 update: 2018-12-24 8:00:00 +0800 author: me cover: [https://img-blog.csdnimg.cn/20181224144920712](https://www.oschin
Stella981 Stella981
1年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置 1、virsh edit centos7 找到“memory”和“vcpu”标签,将 <name>centos7</name> <uuid>2220a6d1-a36a-4fbb-8523-e078b3dfe795</uuid>
Easter79 Easter79
1年前
Twitter的分布式自增ID算法snowflake (Java版)
概述 == 分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。 有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
1年前
MySQL查询按照指定规则排序
1.按照指定(单个)字段排序 select * from table_name order id desc; 2.按照指定(多个)字段排序 select * from table_name order id desc,status desc; 3.按照指定字段和规则排序 selec
Wesley13 Wesley13
1年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
#### 背景描述 # Time: 2019-01-24T00:08:14.705724+08:00 # User@Host: **[**] @ [**] Id: ** # Schema: sentrymeta Last_errno: 0 Killed: 0 # Query_time: 0.315758 Lock_