编写一个 Java GUI 应用程序,
实现图书信息维护子系统,支持图书信息在数据库中的 存储。
Java 应用程序使用 JDBC 连接数据库
并实现图书信息的查询、新增、修改和删除等操作。
图书信息维护子系统(JDBC)系统体系结构如图 2 所示。
有时间在补充
package ex;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
public class MainUI {
public static void main(String[] args) throws SQLException {
LoginFrame frame = new LoginFrame();//实例化登录窗体
frame.setVisible(true);
}
}
class MainFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = -5136005079573007282L;
private final JLabel welcomelabel;
private final JButton addBtn;
private final JButton exitBtn;
private final JButton delete;
// 默认表格模型
private DefaultTableModel model = null;
private JTable table = null;
private JButton updateBtn = null;
public MainFrame() {
super("图书管理系统");
welcomelabel = new JLabel("--------*图书管理系统*--------");
welcomelabel.setFont(new Font(Font.SERIF, Font.BOLD, 40));//设置字体
welcomelabel.setLocation(450, 10);
welcomelabel.setSize(1500, 35);
JPanel loginpane = new JPanel();//创建一个面板容器
JPanel loginpane2 = new JPanel();//创建一个面板容器
JPanel loginpane3 = new JPanel();//创建一个面板容器
loginpane.setBounds(new Rectangle(700, 100, 1000, 700));
loginpane.setBorder(BorderFactory.createEtchedBorder());
addBtn = new JButton("增加数据");
exitBtn = new JButton("退出程序");
delete = new JButton("删除数据");
addBtn.setActionCommand("ADD");
exitBtn.setActionCommand("EXIT");
delete.setActionCommand("DE");
addBtn.addActionListener(this);//绑定监听器
delete.addActionListener(this);
exitBtn.addActionListener(this);//绑定监听器
loginpane.add(welcomelabel);
String[][] datas = {};
String[] titles = {"编号", "书名", "作者", "出版社", "类型", "上架时间"};
model = new DefaultTableModel(datas, titles);
table = new JTable(model);
table.setSize(1500, 1500);
login();
updateBtn = new JButton("刷新数据");
updateBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
login();
}
});
loginpane2.add(new JScrollPane(table));
loginpane3.add(updateBtn, BorderLayout.NORTH);
loginpane3.add(addBtn);
loginpane3.add(delete);
loginpane3.add(exitBtn);
Box vBox = Box.createVerticalBox();
vBox.add(loginpane);
vBox.add(loginpane2);
vBox.add(loginpane3);
setSize(1000, 800);
setContentPane(vBox);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void login() {
while (model.getRowCount() != 0) {
model.removeRow(model.getRowCount() - 1);
}
Mysql mysql = new Mysql();
Connection connection = mysql.connection("root", "147258");
ArrayList<ArrayList<String>> res = null;
try {
res = mysql.find(connection);
for (ArrayList<String> list : res) {
model.addRow(new String[]{list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5)});
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "ADD"://当鼠标点击登录按钮
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
addFrame frame = new addFrame();//创建主界面窗体
frame.setVisible(true);
Thread t = Thread.currentThread();
System.out.println(t.getName());
}
});
break;
case "DE":
System.out.println("))))))))))");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
deleteFrame frame = new deleteFrame();//创建主界面窗体
frame.setVisible(true);
Thread t = Thread.currentThread();
System.out.println(t.getName());
}
});
break;
case "EXIT"://当鼠标点击退出按钮
System.exit(0);
break;
}
}
private String getRandomData() {
String source = "0123456789abcdefghijklmnopqrstuvwxyz";
int len = source.length();
Random random = new Random(System.currentTimeMillis());
return MessageFormat.format("{0}{0}{0}", source.charAt(random.nextInt(len)));
}
}
class LoginFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = -5136005079573007282L;
private final JLabel welcomelabel;
private final JLabel unamelabel;
private final JLabel passwdlabel;
private final JTextField unamefield;
private final JPasswordField passwdfield;
private final JButton loginbtn;
private final JButton exitbtn;
private JLabel rightlabel;
public LoginFrame() {
super("图书管理系统用户登入");
setUndecorated(false);
setResizable(false);
setSize(500, 300);
setLocationRelativeTo(null);
setLayout(null);//设置为空布局
welcomelabel = new JLabel("-------*图书管理系统*--------");
welcomelabel.setFont(new Font(Font.SERIF, Font.BOLD, 28));//设置字体
welcomelabel.setLocation(80, 10);
welcomelabel.setSize(350, 35);
JPanel loginpane = new JPanel(null);//创建一个面板容器
loginpane.setBounds(new Rectangle(70, 60, 360, 185));
loginpane.setBorder(BorderFactory.createEtchedBorder());
unamelabel = new JLabel("用户名:");
unamelabel.setBounds(35, 50, 65, 25);
unamefield = new JTextField();
unamefield.setBounds(110, 50, 200, 25);
passwdlabel = new JLabel("密码:");
passwdlabel.setBounds(35, 85, 65, 25);
passwdfield = new JPasswordField();
passwdfield.setBounds(110, 85, 200, 25);
loginbtn = new JButton("连接");//实例化登录按钮
exitbtn = new JButton("退出");//实例化退出按钮
loginbtn.setActionCommand("LOGIN");
exitbtn.setActionCommand("EXIT");
loginbtn.setBounds(100, 130, 75, 25);
exitbtn.setBounds(235, 130, 75, 25);
loginbtn.addActionListener(this);//绑定监听器
exitbtn.addActionListener(this);//绑定监听器
loginpane.add(unamelabel);
loginpane.add(unamefield);
loginpane.add(passwdlabel);
loginpane.add(passwdfield);
loginpane.add(loginbtn);
loginpane.add(exitbtn);
add(welcomelabel);
add(loginpane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "LOGIN"://当鼠标点击登录按钮
System.out.println("aaa");
String uname = unamefield.getText();//获取用户名文本框中的用户名
String password = new String(passwdfield.getPassword());//获取密码框中的密码
System.out.println(uname + " " + password);
if (uname.equals("root") && password.equals("147258")) {//当用户输入用户名为字符串"zhangsan",密码为字符串"123"时显示主界面
JOptionPane.showMessageDialog(LoginFrame.this, "连接成功!", "系统提示", JOptionPane.YES_NO_CANCEL_OPTION);//显示消息对话框
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MainFrame frame = new MainFrame();//创建主界面窗体
frame.setVisible(true);
}
});
this.dispose();
} else {
JOptionPane.showMessageDialog(LoginFrame.this, "用户名或密码输入错误!", "系统提示", JOptionPane.ERROR_MESSAGE);//显示消息对话框
}
break;
case "EXIT"://当鼠标点击退出按钮
System.exit(0);
break;
}
}
}
class Mysql {
//连接数据库
public Connection connection(String user, String password) {
String driver = "com.mysql.cj.jdbc.Driver";//数据库驱动类所对应的字符串
String URL = "jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
//URL语法格式如下
//jdbc:mysql:是固定的写法,后面跟主机名localhost,3306是默认的MySQL端口号
//serverTimezone=UTC是指定时区时间为世界统一时间
//useUnicode=true是指是否使用Unicode字符集,赋值为true
//characterEncoding=utf-8是指定字符编码格式为UTF8
Connection conn = null;
//Connection接口代表Java程序和数据库的连接对象,只有获得该连接对象后,才能访问数据库,并操作数据表
try {
Class.forName(driver);//加载MySQL数据库驱动
} catch (java.lang.ClassNotFoundException e) {//如果找不到这个类,执行下面的异常处理
System.out.println("驱动程序配置未配置成功!!!");
}
try {
conn = DriverManager.getConnection(URL, user, password);//建立和数据库的连接,并返回表示连接的Connection对象
System.out.println("数据库连接成功!!!");
} catch (Exception e) {//未连接成功,执行下面的异常处理
System.out.println("数据库连接失败!!!");
}
return conn;
}
//获取数据
public ArrayList<ArrayList<String>> find(Connection connection) throws SQLException {
String sql = "select * from books";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
ArrayList<ArrayList<String>> res = new ArrayList<>();
while (resultSet.next()) {
ArrayList<String> list = new ArrayList<>();
list.add(resultSet.getString(1));
list.add(resultSet.getString(2));
list.add(resultSet.getString(3));
list.add(resultSet.getString(4));
list.add(resultSet.getString(5));
list.add(resultSet.getString(6));
res.add(list);
}
Collections.sort(res, new Comparator<ArrayList<String>>() {
@Override
public int compare(ArrayList<String> o1, ArrayList<String> o2) {
return Integer.valueOf(o1.get(0)).compareTo(Integer.valueOf(o2.get(0)));
}
});
return res;
}
//添加数据
public void add(String id, String name, String author, String press, String class_, String time) throws SQLException {
Connection connection = this.connection("root", "147258");
String sql = "insert into books(id,name,author,press,class,time) values ('" + id + "','" + name + "','" + author + "','" + press + "','" + class_ + "','" + time + "')";
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
}
//删除数据
public void delete(String id) throws SQLException {
Connection connection = this.connection("root", "147258");
String sql = "delete from books where id=" + id + "";
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
}
}
class addFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = -5136005079573007282L;
private final JLabel welcomelabel;
private final JLabel idlabel;
private final JLabel namelabel;
private final JLabel authorlabel;
private final JLabel presslabel;
private final JLabel classlabel;
private final JLabel timelabel;
private final JTextField idfield;
private final JTextField namefield;
private final JTextField authorfield;
private final JTextField pressfield;
private final JTextField classfield;
private final JTextField timefield;
private final JButton loginbtn;
private final JButton exitbtn;
private JLabel rightlabel;
public addFrame() {
super("添加图书");
setUndecorated(false);
setResizable(false);
setSize(500, 300);
setLocationRelativeTo(null);
setLayout(null);//设置为空布局
welcomelabel = new JLabel("-------*图书管理系统*--------");
welcomelabel.setFont(new Font(Font.SERIF, Font.BOLD, 28));//设置字体
welcomelabel.setLocation(80, 10);
welcomelabel.setSize(350, 35);
JPanel loginpane = new JPanel(null);//创建一个面板容器
loginpane.setBounds(new Rectangle(70, 60, 360, 185));
loginpane.setBorder(BorderFactory.createEtchedBorder());
idlabel = new JLabel("编号:");
idlabel.setBounds(35, 10, 65, 25);
idfield = new JTextField();
idfield.setBounds(110, 10, 200, 25);
namelabel = new JLabel("书名:");
namelabel.setBounds(35, 30, 65, 25);
namefield = new JTextField();
namefield.setBounds(110, 30, 200, 25);
authorlabel = new JLabel("作者:");
authorlabel.setBounds(35, 50, 65, 25);
authorfield = new JTextField();
authorfield.setBounds(110, 50, 200, 25);
presslabel = new JLabel("出版社:");
presslabel.setBounds(35, 70, 65, 25);
pressfield = new JTextField();
pressfield.setBounds(110, 70, 200, 25);
classlabel = new JLabel("类型:");
classlabel.setBounds(35, 90, 65, 25);
classfield = new JTextField();
classfield.setBounds(110, 90, 200, 25);
timelabel = new JLabel("时间:");
timelabel.setBounds(35, 110, 65, 25);
timefield = new JTextField();
timefield.setBounds(110, 110, 200, 25);
loginbtn = new JButton("提交");//实例化登录按钮
exitbtn = new JButton("取消");//实例化退出按钮
loginbtn.setActionCommand("LOGIN");
exitbtn.setActionCommand("EXIT");
loginbtn.setBounds(100, 140, 75, 25);
exitbtn.setBounds(235, 140, 75, 25);
loginbtn.addActionListener(this);//绑定监听器
exitbtn.addActionListener(this);//绑定监听器
loginpane.add(idlabel);
loginpane.add(idfield);
loginpane.add(namefield);
loginpane.add(namelabel);
loginpane.add(pressfield);
loginpane.add(presslabel);
loginpane.add(classfield);
loginpane.add(classlabel);
loginpane.add(timefield);
loginpane.add(timelabel);
loginpane.add(loginbtn);
loginpane.add(exitbtn);
loginpane.add(authorfield);
loginpane.add(authorlabel);
add(welcomelabel);
add(loginpane);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "LOGIN"://当鼠标点击提交按钮
String id = idfield.getText();//获取用户名文本框中的用户名
String name = namefield.getText();
String author = authorfield.getText();
String press = pressfield.getText();
String class_ = classfield.getText();
String time = timefield.getText();
try {
if (id.equals("")) {
JOptionPane.showMessageDialog(addFrame.this, "提交失败!编号有误!", "系统提示", JOptionPane.ERROR_MESSAGE);
break;
}
new Mysql().add(id, name, author, press, class_, time);
JOptionPane.showMessageDialog(addFrame.this, "提交成功!", "系统提示", JOptionPane.YES_NO_CANCEL_OPTION);//显示消息对话框
this.dispose();
} catch (SQLException throwables) {
throwables.printStackTrace();
JOptionPane.showMessageDialog(addFrame.this, "提交失败!编号有误!", "系统提示", JOptionPane.ERROR_MESSAGE);
}
break;
case "EXIT"://当鼠标点击退出按钮
this.dispose();
break;
}
}
}
class deleteFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = -5136005079573007282L;
private final JLabel welcomelabel;
private final JLabel unamelabel;
private final JTextField unamefield;
private final JButton loginbtn;
private final JButton exitbtn;
private JLabel rightlabel;
public deleteFrame() {
super("删除图书");
setUndecorated(false);
setResizable(false);
setSize(500, 300);
setLocationRelativeTo(null);
setLayout(null);//设置为空布局
welcomelabel = new JLabel("-------*图书管理系统*--------");
welcomelabel.setFont(new Font(Font.SERIF, Font.BOLD, 28));//设置字体
welcomelabel.setLocation(80, 10);
welcomelabel.setSize(350, 35);
JPanel loginpane = new JPanel(null);//创建一个面板容器
loginpane.setBounds(new Rectangle(70, 60, 360, 185));
loginpane.setBorder(BorderFactory.createEtchedBorder());
unamelabel = new JLabel("编号:");
unamelabel.setBounds(35, 50, 65, 25);
unamefield = new JTextField();
unamefield.setBounds(110, 50, 200, 25);
loginbtn = new JButton("删除");//实例化登录按钮
exitbtn = new JButton("取消");//实例化退出按钮
loginbtn.setActionCommand("LOGIN");
exitbtn.setActionCommand("EXIT");
loginbtn.setBounds(100, 130, 75, 25);
exitbtn.setBounds(235, 130, 75, 25);
loginbtn.addActionListener(this);//绑定监听器
exitbtn.addActionListener(this);//绑定监听器
loginpane.add(unamelabel);
loginpane.add(unamefield);
loginpane.add(loginbtn);
loginpane.add(exitbtn);
add(welcomelabel);
add(loginpane);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "LOGIN"://当鼠标点击登录按钮
String id = unamefield.getText();
try {
new Mysql().delete(id);
JOptionPane.showMessageDialog(deleteFrame.this, "删除成功!", "系统提示", JOptionPane.YES_NO_CANCEL_OPTION);//显示消息对话框
this.dispose();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
break;
case "EXIT"://当鼠标点击退出按钮
this.dispose();
break;
}
}
}