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

Wesley13
• 阅读 655

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

码云

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
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:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java爬虫之JSoup使用教程
title:Java爬虫之JSoup使用教程date:201812248:00:000800update:201812248:00:000800author:mecover:https://imgblog.csdnimg.cn/20181224144920712(https://www.oschin
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这