本项目为Java swing项目,在工作环境中基本使用不到,但是很多学校把这个当做编程入门的项目来做,故分享出本项目供初学者参考。
CSDN赞助下载:https://download.csdn.net/download/weixin_44893902/20367467
一、效果演示:
主要功能:
①基本数据维护:
图书类别管理 >> 图书类别添加、图书类别维护
图书管理 >> 图书添加、图书维护
②关于我们
1、登录界面
2、主界面:
3、图书类别维护
4、图书类别添加
5、图书维护
6、图书添加
7、关于我们
可全部缩小到左下角
二、核心代码:
1、Util包 【存放数据库连接工具】
① DBTool(数据库连接工具类)
packagecn.ac.azure.util;importjava.io.IOException;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;importjava.util.Properties;/**
* 数据库连接工具类
* @author 明金同学
*
*/publicclassDBTool{privatestaticString driver;//数据库驱动privatestaticString url;//数据库连接地址privatestaticString user;//数据库连接用户privatestaticString password;//数据库连接密码static{//新建一个properties,用于读取db.properties配置文件Properties p=newProperties();//新建一个字符串,保存配置文件的路径String path="cn//ac//azure//util//db.properties";try{//调用Properties.load通过类加载获得配置文件的输入流
p.load(DBTool.class.getClassLoader().getResourceAsStream(path));//读取配置文件中的配置参数
driver=p.getProperty("driver");//获取驱动
url=p.getProperty("url");//获取数据库连接地址
user=p.getProperty("user");//获取数据库用户
password=p.getProperty("password");//获取数据库密码try{//加载数据库驱动类到程序中Class.forName(driver);}catch(ClassNotFoundException e){
e.printStackTrace();thrownewRuntimeException("加载驱动失败",e);}}catch(IOException e){
e.printStackTrace();thrownewRuntimeException("找不到配置文件",e);}}/**
* 获取数据库连接
* @return 数据库连接对象
* @throws SQLException 提醒调用者捕获异常,并在finally中关闭关闭异常
*/publicstaticConnectiongetConnetion()throwsSQLException{//通过DriverManager获得数据库连接returnDriverManager.getConnection(url, user, password);}/**
* 关闭数据库连接
* @param con
*/publicstaticvoidclose(Connection con){if(con!=null){//如果数据连接不为空try{//关闭数据库连接
con.close();}catch(SQLException e){
e.printStackTrace();thrownewRuntimeException("数据库关闭失败",e);}}}// /**// * 测试数据库连接工具是否可用// * @param args// */// public static void main(String[] args) {// Connection con=null;// try {// con=DBTool.getConnetion();// System.out.println("数据库连接成功!");// } catch (SQLException e) {// System.out.println("数据库连接失败!");// e.printStackTrace();// }finally{// DBTool.close(con);// }// }}
② db.properties(配置文件)
2、model包 【存放实体类】
① Book(图书实体类)
packagecn.ac.azure.model;/**
* 图书实体
* @author 明金同学
*
*/publicclassBook{privateInteger id;//图书idprivateString bookName;//图书名称privateString author;//图书作者privateString sex;//作者性别privateFloat price;//图书价格privateInteger bookTypeId;//图书类别IDprivateString bookTypeName;//图书类别名称privateString bookDesc;//图书描述publicBook(){super();}publicBook(Integer id,String bookName,String author,String sex,Float price,Integer bookTypeId,String bookTypeName,String bookDesc){super();this.id = id;this.bookName = bookName;this.author = author;this.sex = sex;this.price = price;this.bookTypeId = bookTypeId;this.bookTypeName = bookTypeName;this.bookDesc = bookDesc;}publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetBookName(){return bookName;}publicvoidsetBookName(String bookName){this.bookName = bookName;}publicStringgetAuthor(){return author;}publicvoidsetAuthor(String author){this.author = author;}publicStringgetSex(){return sex;}publicvoidsetSex(String sex){this.sex = sex;}publicFloatgetPrice(){return price;}publicvoidsetPrice(Float price){this.price = price;}publicIntegergetBookTypeId(){return bookTypeId;}publicvoidsetBookTypeId(Integer bookTypeId){this.bookTypeId = bookTypeId;}publicStringgetBookTypeName(){return bookTypeName;}publicvoidsetBookTypeName(String bookTypeName){this.bookTypeName = bookTypeName;}publicStringgetBookDesc(){return bookDesc;}publicvoidsetBookDesc(String bookDesc){this.bookDesc = bookDesc;}@OverridepublicStringtoString(){return"Book [测试="+ id +", bookName="+ bookName +", author="+ author +", sex="+ sex +", price="+ price
+", bookTypeId="+ bookTypeId +", bookTypeName="+ bookTypeName +", bookDesc="+ bookDesc +"]";}}
② BookType(图书类别实体类)
packagecn.ac.azure.model;/**
* 图书类别实体
* @author 明金同学
*
*/publicclassBookType{privateint id;//定义IDprivateString bookTypeName;//定义图书类别名称privateString bookTypeDesc;//定义图书类别描述//无参构造器publicBookType(){}//有参构造函数publicBookType(String bookTypeName,String bookTypeDesc){super();this.bookTypeName = bookTypeName;this.bookTypeDesc = bookTypeDesc;}publicBookType(int id,String bookTypeName,String bookTypeDesc){super();this.id = id;this.bookTypeName = bookTypeName;this.bookTypeDesc = bookTypeDesc;}publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetBookTypeName(){return bookTypeName;}publicvoidsetBookTypeName(String bookTypeName){this.bookTypeName = bookTypeName;}publicStringgetBookTypeDesc(){return bookTypeDesc;}publicvoidsetBookTypeDesc(String bookTypeDesc){this.bookTypeDesc = bookTypeDesc;}@OverridepublicStringtoString(){return"BookType [id="+ id +", bookTypeName="+ bookTypeName +", bookTypeDesc="+ bookTypeDesc +"]";}}
③ User(用户实体类)
packagecn.ac.azure.model;/**
* 用户实体
* @author 明金同学
*
*/publicclassUser{privateint id;//用户idprivateString username;//用户名称privateString password;//用户密码publicUser(){}@OverridepublicStringtoString(){return"User [id="+ id +", username="+ username +", password="+ password +"]";}publicUser(String username,String password){super();this.username = username;this.password = password;}publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}}
3、Dao包 【数据库访问层】
① BookDao(图书dao类)
packagecn.ac.azure.dao;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importcn.ac.azure.model.Book;/**
* 图书dao类
* @author 明金同学
*
*/publicclassBookDao{/**
* 图书添加
* @param con 数据库库连接对象
* @param book 添加的图书对象
* @return 返回添加操作的数据库记录数
* @throws SQLException 抛出数据库异常
*/publicintadd(Connection con,Book book)throwsSQLException{//拼写sql插入语句String sql="insert into t_book values(null,'"+book.getBookName()+"','"+book.getAuthor()+"','"+book.getSex()+"','"+book.getPrice()+"','"+book.getBookTypeId()+"','"+book.getBookTypeName()+"','"+book.getBookDesc()+"')";System.out.println(sql);//获得预编译对象psPreparedStatement ps=con.prepareStatement(sql);//设置ps参数/*ps.setString(1,book.getBookName()); //设置图书名称
ps.setString(2,book.getAuthor()); //设置图书作者
ps.setString(3, book.getSex()); //设置作者性别
ps.setFloat(4, book.getPrice()); //设置图书价格
ps.setInt(5, book.getBookTypeId()); //设置图书类别ID
ps.setString(6, book.getBookDesc()); //设置图书描述
*///执行sql语句,并返回插入的记录数return ps.executeUpdate();}/**
* 图书查询
* @param con 数据库连接对象
* @param book 图书对象
* @return 查询的结果集
* @throws SQLException 抛出数据库异常
*/publicResultSetsearch(Connection con,Book book)throwsSQLException{//定义图书名称String bookName=null;//定义图书作者String author=null;//定义图书类别名称String bookTypeName=null;//如果图书不为空的话,就为前三个字段赋值,按照条件查询if(book!=null){
bookName=book.getBookName();
author=book.getAuthor();
bookTypeName=book.getBookTypeName();}//定义一个字符串缓冲对象类存储查询添加StringBuilder sb=newStringBuilder("select * from t_book b , t_bookType bt where b.bookTypeId=bt.id ");//查询条件有图书名称if(!(bookName==null||"".equals(bookName.trim()))){
sb.append("and b.bookName like '%"+bookName+"%' ");}//查询条件有图书作者if(!(author==null||"".equals(author.trim()))){
sb.append("and b.author like '%"+author+"%' ");}//查询条件有图书类别名称if(!(bookTypeName==null||"".equals(bookTypeName.trim()))){
sb.append("and bt.bookTypeName like '%"+bookTypeName+"%' ");}//从sb生成sql语句String sql=sb.toString();//获取预处理对象PreparedStatement ps=con.prepareStatement(sql);//执行查询,并返回结果集return ps.executeQuery();}/**
* 图书修改
* @param con 数据库连接对象
* @param book 修改的图书对象
* @return 返回修改改变的记录数
* @throws SQLException 抛出数据库异常,同时提醒调用者关闭数据库
*/publicintupdate(Connection con,Book book)throwsSQLException{//编写sql语句String sql="update t_book set bookName=?,author=?,sex=?,"+"price=?,bookTypeId=?,bookDesc=? where id=?";//获取预编译对象psPreparedStatement ps=con.prepareStatement(sql);//设置ps对象
ps.setString(1, book.getBookName());//图书名称
ps.setString(2, book.getAuthor());//图书作者
ps.setString(3,book.getSex());//作者性别
ps.setFloat(4, book.getPrice());//图书价格
ps.setInt(5, book.getBookTypeId());//图书类型Id
ps.setString(6, book.getBookDesc());//图书描述
ps.setInt(7, book.getId());//执行修改并返回改变的记录数return ps.executeUpdate();}/**
* 图书删除
* @param con 数据库连接对象
* @param id 删除图书的id
* @return 返回删除的记录数
* @throws SQLException 抛出数据库异常,同时提醒调用者关闭数据库
*/publicintdelete(Connection con,int id)throwsSQLException{//编写sql语句String sql="delete from t_book where id=?";//获取预编译对象psPreparedStatement ps=con.prepareStatement(sql);//设置ps参数
ps.setInt(1, id);//执行DML删除语句并返回删除的记录数return ps.executeUpdate();}}
② BookTypeDao(图书类别dao类)
packagecn.ac.azure.dao;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importcn.ac.azure.model.BookType;/**
* 图书类别dao类
* @author 明金同学
*
*/publicclassBookTypeDao{/**
* 图书类别添加
* @param con 数据库连接对象
* @param bookType 要添加的图书类别
* @return 返回数据库操作的记录数
* @throws SQLException
*/publicintadd(Connection con,BookType bookType)throwsSQLException{//拼写sql插入语句String sql="insert into t_bookType values(null,?,?)";//创建预编译对象psPreparedStatement ps=con.prepareStatement(sql);//设置ps参数
ps.setString(1, bookType.getBookTypeName());//设置bookTypeName
ps.setString(2, bookType.getBookTypeDesc());//设置bookTypeDesc//返回数据库操作的记录数return ps.executeUpdate();}/**
* 图书类别查询
* @param con 数据库连接对象
* @param bookType 查询的图书类别
* @return 返回查询的结果集
* @throws SQLException 抛出数据库异常
*/publicResultSetsearch(Connection con,BookType bookType)throwsSQLException{/*
* 思路:当jdbc查询数据库有多个条件从外部输入时,这是最好创建一个字符串缓冲类来添加条件到sql语句中。
* 同时,不知道有哪些条件是第一条件,无法确定where关键字的所在,于是添加条件都用(and 条件)
* 最后字符串转换成字符串时在将第一个and替换成where
*///定义一个图书类别名称String bookTypeName=null;if(bookType!=null){//如果类别对象不为空的话,就获取它的类别名称
bookTypeName=bookType.getBookTypeName();}//创建一个字符串缓冲类StringBuilder sb=newStringBuilder("select * from t_bookType");//添加查询语句的条件(and + 条件)if(!(bookTypeName==null||"".equals(bookTypeName.trim()))){//jdbc中,数据库字符串要用单引号括起来
sb.append(" and bookTypeName like '%"+bookType.getBookTypeName()+"%'");}//将字符串缓冲对象转换成字符串,同时把第一个and替换成whereString sql=sb.toString().replaceFirst("and","where");//获取预编译对象PreparedStatement ps=con.prepareStatement(sql);//返回ps执行查询之后的结果集return ps.executeQuery();}/**
* 图书类别修改
* @param con 数据路连接对象
* @param bookType 要修改的图书类别
* @return 返回数据库更新的记录数
* @throws SQLException 抛出数据库异常
*/publicintupdate(Connection con,BookType bookType)throwsSQLException{//拼写sql更新语句String sql="update t_bookType set bookTypeName=? , bookTypeDesc=? where id=?";//获取预编译对象psPreparedStatement ps=con.prepareStatement(sql);//设置ps参数
ps.setString(1,bookType.getBookTypeName());
ps.setString(2,bookType.getBookTypeDesc());
ps.setInt(3, bookType.getId());//赶回ps更新数据库的记录数return ps.executeUpdate();}/**
* 删除数据库记录
* @param con 数据库连接对象
* @param id 传入删除记录的id
* @return 返回删除的记录数
* @throws SQLException 抛出数据库异常
*/publicintdelete(Connection con,String id)throwsSQLException{//拼写sql删除语句String sql="delete from t_bookType where id=?";//获取预编译对象psPreparedStatement ps=con.prepareStatement(sql);//设置ps参数
ps.setString(1, id);//执行ps更行操作,并返回改变的数据记录条数return ps.executeUpdate();}}
③ UserDao(用户数据访问对象)
packagecn.ac.azure.dao;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importcn.ac.azure.model.User;/**
* 用户数据访问对象
* @author 明金同学
*
*/publicclassUserDao{/**
* 登录验证
* @param con 数据库连接对象
* @param user 登录的账户
* @return 返回一个用户对象,为null,则登录失败;反之,则登录成功
* @throws Exception 让调用者处理异常
*/publicUserlogin(Connection con,User user)throwsSQLException{//定义一个返回用户对象User resultUser=null;//拼写sql查询语句String sql="select * from t_user where username=? and password=?";//获取sql语句预编译对象PreparedStatement ps=con.prepareStatement(sql);//设置ps参数
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());//ps执行sql查询语句返回结果集ResultSet rs=ps.executeQuery();//遍历结果集while(rs.next()){//初始化返回用户对象
resultUser=newUser();
resultUser.setId(rs.getInt("id"));//设置用户id
resultUser.setUsername(rs.getString("username"));//设置用户名称
resultUser.setPassword(rs.getString("password"));//设置用户密码}//返回用户对象return resultUser;}}
4、View包 【视图层】
① LoginFrame(登录界面)
packagecn.ac.azure.view;importjava.awt.EventQueue;importjava.awt.Font;importjava.awt.Toolkit;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.sql.Connection;importjava.sql.SQLException;importjavax.swing.GroupLayout;importjavax.swing.GroupLayout.Alignment;importjavax.swing.ImageIcon;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JPasswordField;importjavax.swing.JTextField;importjavax.swing.LayoutStyle.ComponentPlacement;importjavax.swing.UIManager;importjavax.swing.UnsupportedLookAndFeelException;importjavax.swing.border.EmptyBorder;importcn.ac.azure.dao.UserDao;importcn.ac.azure.model.User;importcn.ac.azure.util.DBTool;publicclassLoginFrameextendsJFrame{static{try{// 这里是皮肤包可以随意切换// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel");javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.mint.MintLookAndFeel");}catch(ClassNotFoundException|InstantiationException|IllegalAccessException|UnsupportedLookAndFeelException e){
e.printStackTrace();}}privateJPanel contentPane;privateJTextField usernameText;privateJPasswordField passwordText;privateJButton loginBtn;privateJButton resetBtn;/**
* Launch the application.
*/publicstaticvoidmain(String[] args){EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{LoginFrame frame =newLoginFrame();
frame.setVisible(true);}catch(Exception e){
e.printStackTrace();}}});}/**
* Create the frame.
*/publicLoginFrame(){//改变系统默认字体Font font =newFont("Dialog",Font.PLAIN,12);java.util.Enumeration<Object> keys =UIManager.getDefaults().keys();while(keys.hasMoreElements()){Object key = keys.nextElement();Object value =UIManager.get(key);if(value instanceofjavax.swing.plaf.FontUIResource){UIManager.put(key, font);}}setIconImage(Toolkit.getDefaultToolkit().getImage(LoginFrame.class.getResource("/images/logo.png")));setResizable(false);setTitle("管理员登录");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100,100,450,300);
contentPane =newJPanel();
contentPane.setBorder(newEmptyBorder(5,5,5,5));setContentPane(contentPane);JLabel lblNewLabel =newJLabel("\u56FE\u4E66\u7BA1\u7406\u7CFB\u7EDF");
lblNewLabel.setFont(newFont("宋体",Font.BOLD,22));
lblNewLabel.setIcon(newImageIcon(LoginFrame.class.getResource("/images/logo.png")));JLabel lblNewLabel_1 =newJLabel("用户名 :");
lblNewLabel_1.setIcon(newImageIcon(LoginFrame.class.getResource("/images/userName.png")));
usernameText =newJTextField();
usernameText.setColumns(10);JLabel lblNewLabel_2 =newJLabel("密 码 :");
lblNewLabel_2.setIcon(newImageIcon(LoginFrame.class.getResource("/images/password.png")));
passwordText =newJPasswordField();//添加登陆按钮
loginBtn =newJButton("登录");
loginBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){loginActionPerformed(e);}});
loginBtn.setIcon(newImageIcon(LoginFrame.class.getResource("/images/login.png")));//添加重置按钮
resetBtn =newJButton("重置");
resetBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){resetActionPerformed(e);}});
resetBtn.setIcon(newImageIcon(LoginFrame.class.getResource("/images/reset.png")));GroupLayout gl_contentPane =newGroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane.createSequentialGroup().addGap(106).addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addComponent(lblNewLabel).addGroup(gl_contentPane.createSequentialGroup().addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane.createSequentialGroup().addPreferredGap(ComponentPlacement.RELATED).addComponent(lblNewLabel_1).addPreferredGap(ComponentPlacement.RELATED).addComponent(usernameText,GroupLayout.PREFERRED_SIZE,142,GroupLayout.PREFERRED_SIZE)).addGroup(gl_contentPane.createSequentialGroup().addComponent(lblNewLabel_2).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(passwordText,GroupLayout.PREFERRED_SIZE,144,GroupLayout.PREFERRED_SIZE)).addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup().addGap(16).addComponent(loginBtn).addPreferredGap(ComponentPlacement.RELATED,GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addComponent(resetBtn))).addPreferredGap(ComponentPlacement.RELATED))).addContainerGap(105,GroupLayout.PREFERRED_SIZE)));
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane.createSequentialGroup().addGap(25).addComponent(lblNewLabel).addGap(18).addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel_1).addComponent(usernameText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(18).addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel_2).addComponent(passwordText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(29).addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE).addComponent(loginBtn).addComponent(resetBtn)).addContainerGap()));
contentPane.setLayout(gl_contentPane);//设置窗口居中this.setLocationRelativeTo(null);}/**
* 登录事件处理
* @param evt
*/privatevoidloginActionPerformed(ActionEvent evt){//从输入框获取用户名String username=usernameText.getText().trim();//从输入框获取密码String password=passwordText.getText().trim();//用户名不能为空或空字符串,否则结束事件处理if(username==null||"".equals(username)){JOptionPane.showMessageDialog(null,"用户名不能为空");return;}//用户名不能为空或空字符串否则结束事件处理if(password==null||"".equals(password)){JOptionPane.showMessageDialog(null,"密码不能为空");return;}//将从输入框获得信息新建一个对象User user=newUser(username, password);//定义数据库连接Connection con=null;try{//利用数据库工具类获取数据库连接
con=DBTool.getConnetion();//新建一个用户数据访问对象UserDao userDao=newUserDao();//调用其登录验证方法获取一个用户对象User currUser=userDao.login(con, user);//判断返回的用户对象if(currUser!=null){//不为空,表示登录成功//进入主界面,并设置可见newMainFrame().setVisible(true);//释放当前窗口资源dispose();}else{//为空,表示登录不成功JOptionPane.showMessageDialog(null,"登录失败(u_u)");}}catch(SQLException e){
e.printStackTrace();thrownewRuntimeException("登录失败",e);}finally{//关闭数据库连接DBTool.close(con);}}/**
* 重置事件处理
* @param evt
*/privatevoidresetActionPerformed(ActionEvent evt){
usernameText.setText("");
passwordText.setText("");}}
② MainFrame(主界面)
packagecn.ac.azure.view;importjava.awt.BorderLayout;importjava.awt.Color;importjava.awt.EventQueue;importjava.awt.Font;importjavax.swing.ImageIcon;importjavax.swing.JDesktopPane;importjavax.swing.JFrame;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.UIManager;importjavax.swing.UnsupportedLookAndFeelException;importjavax.swing.border.EmptyBorder;importjava.awt.event.ActionListener;importjava.awt.event.ActionEvent;publicclassMainFrameextendsJFrame{static{try{// 这里是皮肤包可以随意切换// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel");javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel");// javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.mint.MintLookAndFeel");}catch(ClassNotFoundException|InstantiationException|IllegalAccessException|UnsupportedLookAndFeelException e){
e.printStackTrace();}}privatestaticfinallong serialVersionUID =1L;//定义内容窗格privateJPanel contentPane;//定义桌面窗格privateJDesktopPane table;/**
* Launch the application.
*/publicstaticvoidmain(String[] args){EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{MainFrame frame =newMainFrame();
frame.setVisible(true);}catch(Exception e){
e.printStackTrace();}}});}/**
* Create the frame.
*/publicMainFrame(){//改变系统默认字体Font font =newFont("Dialog",Font.PLAIN,12);java.util.Enumeration<Object> keys =UIManager.getDefaults().keys();while(keys.hasMoreElements()){Object key = keys.nextElement();Object value =UIManager.get(key);if(value instanceofjavax.swing.plaf.FontUIResource){UIManager.put(key, font);}}setTitle("\u56FE\u4E66\u7BA1\u7406\u7CFB\u7EDF\u4E3B\u754C\u9762");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100,100,450,300);JMenuBar menuBar =newJMenuBar();
menuBar.setToolTipText("");setJMenuBar(menuBar);JMenu menu =newJMenu("\u57FA\u672C\u6570\u636E\u7EF4\u62A4 ");
menu.setIcon(newImageIcon(MainFrame.class.getResource("/images/base.png")));
menuBar.add(menu);JMenu mnNewMenu =newJMenu("\u56FE\u4E66\u7C7B\u522B\u7BA1\u7406 ");
mnNewMenu.setIcon(newImageIcon(MainFrame.class.getResource("/images/bookTypeManager.png")));
menu.add(mnNewMenu);//图书类别添加JMenuItem menuItem =newJMenuItem("\u56FE\u4E66\u7C7B\u522B\u6DFB\u52A0");
menuItem.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){BookTypeAddInterFrame bookTypeAddInterFrame=newBookTypeAddInterFrame();
bookTypeAddInterFrame.setVisible(true);
table.add(bookTypeAddInterFrame);}});
menuItem.setIcon(newImageIcon(MainFrame.class.getResource("/images/add.png")));
mnNewMenu.add(menuItem);//图书类别维护JMenuItem menuItem_1 =newJMenuItem("\u56FE\u4E66\u7C7B\u522B\u7EF4\u62A4");
menuItem_1.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){BookTypeManageInterFrame bookTypeManageInterFrame=newBookTypeManageInterFrame();
bookTypeManageInterFrame.setVisible(true);
table.add(bookTypeManageInterFrame);}});
menuItem_1.setIcon(newImageIcon(MainFrame.class.getResource("/images/edit.png")));
mnNewMenu.add(menuItem_1);JMenu menu_1 =newJMenu("\u56FE\u4E66\u7BA1\u7406");
menu_1.setIcon(newImageIcon(MainFrame.class.getResource("/images/bookManager.png")));
menu.add(menu_1);//图书添加JMenuItem menuItem_2 =newJMenuItem("\u56FE\u4E66\u6DFB\u52A0");
menuItem_2.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){BookAddInterFrame bookAddInterFrame=newBookAddInterFrame();
bookAddInterFrame.setVisible(true);
table.add(bookAddInterFrame);}});
menuItem_2.setIcon(newImageIcon(MainFrame.class.getResource("/images/add.png")));
menu_1.add(menuItem_2);//图书维护JMenuItem menuItem_3 =newJMenuItem("\u56FE\u4E66\u7EF4\u62A4");
menuItem_3.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){BookManageInterFrame bookManageInterFrame=newBookManageInterFrame();
bookManageInterFrame.setVisible(true);
table.add(bookManageInterFrame);}});
menuItem_3.setIcon(newImageIcon(MainFrame.class.getResource("/images/edit.png")));
menu_1.add(menuItem_3);//安全退出JMenuItem menuItem_4 =newJMenuItem("\u5B89\u5168\u9000\u51FA");
menuItem_4.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){//弹出退出确认提示框int res=JOptionPane.showConfirmDialog(null,"确定要退出吗?");//确定退出if(res==JOptionPane.OK_OPTION){dispose();}//否则继续留在该界面}});
menuItem_4.setIcon(newImageIcon(MainFrame.class.getResource("/images/exit.png")));
menu.add(menuItem_4);JMenu menu_2 =newJMenu("\u5173\u4E8E\u6211\u4EEC");
menu_2.setIcon(newImageIcon(MainFrame.class.getResource("/images/about.png")));
menuBar.add(menu_2);//关于我们JMenuItem menuItem_5 =newJMenuItem("\u5173\u4E8E\u6211\u4EEC");
menuItem_5.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){//新建一个图书内部窗体LibraryInterFrame libraryInnerFrame=newLibraryInterFrame();//显示图书内部窗体
libraryInnerFrame.setVisible(true);//将图书内部窗体显示到主界面桌面窗格中
table.add(libraryInnerFrame);}});
menuItem_5.setIcon(newImageIcon(MainFrame.class.getResource("/images/about.png")));
menu_2.add(menuItem_5);
contentPane =newJPanel();
contentPane.setBorder(newEmptyBorder(5,5,5,5));
contentPane.setLayout(newBorderLayout(0,0));setContentPane(contentPane);//定义主界面桌面窗格界面,用于装载内部窗体
table =newJDesktopPane();
table.setBackground(Color.LIGHT_GRAY);
contentPane.add(table,BorderLayout.CENTER);//设置窗口最大化setExtendedState(JFrame.MAXIMIZED_BOTH);}}
③ BookTypeManageInterFrame(图书类别管理界面)
packagecn.ac.azure.view;importjava.awt.EventQueue;importjava.awt.Font;importjava.sql.Connection;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Vector;importjavax.swing.GroupLayout;importjavax.swing.GroupLayout.Alignment;importjavax.swing.ImageIcon;importjavax.swing.JButton;importjavax.swing.JInternalFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JScrollPane;importjavax.swing.JTable;importjavax.swing.JTextField;importjavax.swing.UIManager;importjavax.swing.LayoutStyle.ComponentPlacement;importjavax.swing.table.DefaultTableModel;importcn.ac.azure.dao.BookTypeDao;importcn.ac.azure.model.BookType;importcn.ac.azure.util.DBTool;importjava.awt.event.ActionListener;importjava.awt.event.ActionEvent;importjavax.swing.JPanel;importjavax.swing.border.LineBorder;importjavax.swing.border.TitledBorder;importjavax.swing.JTextArea;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;publicclassBookTypeManageInterFrameextendsJInternalFrame{privateJTextField s_bookTypeNameText;privateJTable bookTypeTable;privateBookTypeDao bookTypeDao=newBookTypeDao();privateJTextField idText;privateJTextField bookTypeNameText;privateJTextArea bookTypeDescText;/**
* Launch the application.
*/publicstaticvoidmain(String[] args){EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{BookTypeManageInterFrame frame =newBookTypeManageInterFrame();
frame.setVisible(true);}catch(Exception e){
e.printStackTrace();}}});}/**
* Create the frame.
*/publicBookTypeManageInterFrame(){//改变系统默认字体Font font =newFont("Dialog",Font.PLAIN,12);java.util.Enumeration keys =UIManager.getDefaults().keys();while(keys.hasMoreElements()){Object key = keys.nextElement();Object value =UIManager.get(key);if(value instanceofjavax.swing.plaf.FontUIResource){UIManager.put(key, font);}}setIconifiable(true);setClosable(true);setTitle("图书类别管理");setBounds(400,100,535,489);JScrollPane scrollPane =newJScrollPane();JLabel label =newJLabel("图书类别名称:");
s_bookTypeNameText =newJTextField();
s_bookTypeNameText.setColumns(10);//查询按钮JButton searchBtn =newJButton("查询");
searchBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){searchActionPerformed(e);}});
searchBtn.setIcon(newImageIcon(BookTypeManageInterFrame.class.getResource("/images/search.png")));JPanel panel =newJPanel();
panel.setBorder(newTitledBorder(null,"\u8868\u5355\u64CD\u4F5C",TitledBorder.LEADING,TitledBorder.TOP,null,null));GroupLayout groupLayout =newGroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(56).addComponent(label).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(s_bookTypeNameText,GroupLayout.PREFERRED_SIZE,167,GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED,54,Short.MAX_VALUE).addComponent(searchBtn).addGap(71)).addGroup(groupLayout.createSequentialGroup().addGap(36).addGroup(groupLayout.createParallelGroup(Alignment.TRAILING,false).addComponent(panel,Alignment.LEADING,GroupLayout.DEFAULT_SIZE,GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addComponent(scrollPane,Alignment.LEADING)).addContainerGap(31,Short.MAX_VALUE)));
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(27).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(searchBtn).addComponent(label).addComponent(s_bookTypeNameText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(18).addComponent(scrollPane,GroupLayout.PREFERRED_SIZE,167,GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(panel,GroupLayout.DEFAULT_SIZE,194,Short.MAX_VALUE).addContainerGap()));JLabel label_1 =newJLabel("编号:");
idText =newJTextField();
idText.setEditable(false);
idText.setColumns(10);JLabel label_2 =newJLabel("图书类别名称:");
bookTypeNameText =newJTextField();
bookTypeNameText.setColumns(10);JLabel label_3 =newJLabel("描述:");
bookTypeDescText =newJTextArea();//修改按钮JButton modifyBtn =newJButton("修改");
modifyBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){bookTypeUpdateActionPerformed(e);}});
modifyBtn.setIcon(newImageIcon(BookTypeManageInterFrame.class.getResource("/images/modify.png")));//删除按钮JButton deleteBtn =newJButton("删除");
deleteBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){bookTypeDeleteActionPerformed(e);}});
deleteBtn.setIcon(newImageIcon(BookTypeManageInterFrame.class.getResource("/images/delete.png")));GroupLayout gl_panel =newGroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addGap(19).addGroup(gl_panel.createParallelGroup(Alignment.TRAILING).addGroup(Alignment.LEADING, gl_panel.createSequentialGroup().addComponent(label_1).addPreferredGap(ComponentPlacement.RELATED).addComponent(idText,GroupLayout.PREFERRED_SIZE,47,GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(label_2).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(bookTypeNameText,GroupLayout.PREFERRED_SIZE,166,GroupLayout.PREFERRED_SIZE)).addGroup(Alignment.LEADING, gl_panel.createSequentialGroup().addComponent(label_3).addPreferredGap(ComponentPlacement.RELATED).addComponent(bookTypeDescText)).addGroup(gl_panel.createSequentialGroup().addComponent(modifyBtn).addGap(54).addComponent(deleteBtn).addGap(64))).addContainerGap(56,GroupLayout.PREFERRED_SIZE)));
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addContainerGap().addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(label_1).addComponent(idText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(label_2).addComponent(bookTypeNameText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(27).addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(label_3).addComponent(bookTypeDescText,GroupLayout.PREFERRED_SIZE,51,GroupLayout.PREFERRED_SIZE)).addGap(18).addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(deleteBtn).addComponent(modifyBtn)).addContainerGap(GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)));
panel.setLayout(gl_panel);//表格
bookTypeTable =newJTable();//表格鼠标点击事件
bookTypeTable.addMouseListener(newMouseAdapter(){@OverridepublicvoidmousePressed(MouseEvent e){bookTypeTableMousePressed(e);}});
bookTypeTable.setModel(newDefaultTableModel(newObject[][]{},newString[]{"编号","图书类别名称","图书类别描述"}){boolean[] columnEditables =newboolean[]{false,false,false};publicbooleanisCellEditable(int row,int column){return columnEditables[column];}});
bookTypeTable.getColumnModel().getColumn(1).setPreferredWidth(96);
bookTypeTable.getColumnModel().getColumn(2).setPreferredWidth(185);
scrollPane.setViewportView(bookTypeTable);getContentPane().setLayout(groupLayout);//设置文本域边框
bookTypeDescText.setBorder(newLineBorder(newjava.awt.Color(127,157,185),1,false));//构造函数中调用填充表格数据函数,全部图书类别显示在表格中fillTable(newBookType());}/**
* 图书类别删除事件处理
* @param evt
*/privatevoidbookTypeDeleteActionPerformed(ActionEvent evt){//获得表单中编号的值idString id=idText.getText();//判断表单有没有选中的图书类别记录if(id==null||"".equals(id.trim())){JOptionPane.showMessageDialog(null,"请选择要修改的记录!");return;}//弹出确认框,是否要删除图书类别记录int res=JOptionPane.showConfirmDialog(null,"你确定要删除该条记录吗?");if(res!=0){//否return;//结束该事件处理函数}//定义数据库连接Connection con=null;try{//获取数据路连接
con=DBTool.getConnetion();int row=bookTypeDao.delete(con, id);if(row==1){//删除成功,弹出提示框JOptionPane.showMessageDialog(null,"修改数据成功(n_n)");//清空表单数据resetValue();//刷新表格记录显示fillTable(newBookType());}else{//删除失败,弹出提示框JOptionPane.showMessageDialog(null,"修改数据失败(u_u)");}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("删除记录失败!",e);}finally{//关闭数据库DBTool.close(con);}}/**
* 图书类别修改事件处理
* @param evt
*/privatevoidbookTypeUpdateActionPerformed(ActionEvent evt){//获取表单操作各个文本框的值String id=idText.getText();String bookTypeName=bookTypeNameText.getText();String bookTypeDesc=bookTypeDescText.getText();//判断表单有没有选中的图书类别记录if(id==null||"".equals(id.trim())){JOptionPane.showMessageDialog(null,"请选择要修改的记录!");return;}//图书类别名称不能为空if(bookTypeName==null||"".equals(bookTypeName.trim())){JOptionPane.showMessageDialog(null,"图书类别名称不能为空!");return;}//利用表单的数据新建一个图书类别对象BookType bookType=newBookType(Integer.parseInt(id), bookTypeName, bookTypeDesc);//定义数据库连接对象Connection con=null;try{//获取数据库连接
con=DBTool.getConnetion();//执行图书类别dao类的修改记录方法int res=bookTypeDao.update(con, bookType);if(res==1){//修改成功,弹出提示框JOptionPane.showMessageDialog(null,"修改数据成功(n_n)");//清空表单数据resetValue();//刷新表格记录显示fillTable(newBookType());}else{//修改失败,弹出提示框JOptionPane.showMessageDialog(null,"修改数据失败(u_u)");}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("修改图书类别失败",e);}finally{//关闭数据路连接DBTool.close(con);}}/**
* 表格鼠标点击事件处理
* @param e
*/privatevoidbookTypeTableMousePressed(MouseEvent e){//获取表格选中的行int row=bookTypeTable.getSelectedRow();//获取表中选中行的第一列的值并显示在idText框中
idText.setText(String.valueOf(bookTypeTable.getValueAt(row,0)));//获取表中选中行的第二列的值并显示在bookTypeNameText框中
bookTypeNameText.setText((String)bookTypeTable.getValueAt(row,1));//获取表中选中行的第三列的值并显示在bookTypeDescText框中
bookTypeDescText.setText((String)bookTypeTable.getValueAt(row,2));}/**
* 图书类别查询事件处理
* @param evt
*/privatevoidsearchActionPerformed(ActionEvent evt){//获取图书类别输入框里的内容String s_bookTypeName=s_bookTypeNameText.getText();//新建一个图书类别并初始化BookType bookType=newBookType();//将输入框的内容设置成新建图书类别的图书类别名称
bookType.setBookTypeName(s_bookTypeName);//根据图书类别查询图书类别fillTable(bookType);}/**
* 在表格中填充数据
* @param bookType 传入bookType对象
*/privatevoidfillTable(BookType bookType){//获取表格的模型DefaultTableModel dtm=(DefaultTableModel) bookTypeTable.getModel();//清空表格
dtm.setRowCount(0);//定义数据库连接Connection con=null;try{//获取数据库连接
con=DBTool.getConnetion();//调用BookTyPeDao的查询方法,并获得其查询的结果集ResultSet rs=bookTypeDao.search(con, bookType);//遍历结果集while(rs.next()){//新建一个vector并初始化Vector v=newVector();
v.add(rs.getInt("id"));//向vector中添加id
v.add(rs.getString("bookTypeName"));//向vector中添加bookTypeName
v.add(rs.getString("bookTypeDesc"));//向vector中添加bookTypeDesc//将vector中的数据显示到表格中
dtm.addRow(v);}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("查询失败");}finally{//关闭数据库DBTool.close(con);}}/**
* 清空表单数据
*/privatevoidresetValue(){
idText.setText("");
bookTypeNameText.setText("");
bookTypeDescText.setText("");
s_bookTypeNameText.setText("");}}
④ BookTypeAddInterFrame(图书类别添加界面)
packagecn.ac.azure.view;importjava.awt.EventQueue;importjava.awt.Font;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.sql.Connection;importjava.sql.SQLException;importjavax.swing.GroupLayout;importjavax.swing.GroupLayout.Alignment;importjavax.swing.JButton;importjavax.swing.JInternalFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JTextArea;importjavax.swing.JTextField;importjavax.swing.UIManager;importjavax.swing.LayoutStyle.ComponentPlacement;importjavax.swing.border.LineBorder;importcn.ac.azure.dao.BookTypeDao;importcn.ac.azure.model.BookType;importcn.ac.azure.util.DBTool;/**
* 图书类别内部添加窗体
* @author green
*
*/publicclassBookTypeAddInterFrameextendsJInternalFrame{//图书类别名称输入框privateJTextField bookTypeNameText;//图书类别描述输入框privateJTextArea bookTypeDescText;//重置按钮privateJButton resetBtn;//添加按钮privateJButton addBtn;//图书类别数据库访问对象privateBookTypeDao bookTypeDao;/**
* Launch the application.
*/publicstaticvoidmain(String[] args){EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{BookTypeAddInterFrame frame =newBookTypeAddInterFrame();
frame.setVisible(true);}catch(Exception e){
e.printStackTrace();}}});}/**
* Create the frame.
*/publicBookTypeAddInterFrame(){//改变系统默认字体Font font =newFont("Dialog",Font.PLAIN,12);java.util.Enumeration keys =UIManager.getDefaults().keys();while(keys.hasMoreElements()){Object key = keys.nextElement();Object value =UIManager.get(key);if(value instanceofjavax.swing.plaf.FontUIResource){UIManager.put(key, font);}}setClosable(true);setIconifiable(true);setTitle("图书类别添加");setBounds(100,100,487,342);JLabel label =newJLabel("图书类别名称:");
bookTypeNameText =newJTextField();
bookTypeNameText.setColumns(10);JLabel label_1 =newJLabel("图书类别描述:");
bookTypeDescText =newJTextArea();//添加按钮
addBtn =newJButton("添加");
addBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){addActionPerformed(e);}});//重置按钮
resetBtn =newJButton("重置");
resetBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){resetActionPerformed(e);}});GroupLayout groupLayout =newGroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(128).addComponent(addBtn).addGap(91).addComponent(resetBtn)).addGroup(groupLayout.createSequentialGroup().addGap(89).addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(bookTypeDescText).addGroup(groupLayout.createSequentialGroup().addComponent(label).addPreferredGap(ComponentPlacement.RELATED).addComponent(bookTypeNameText,GroupLayout.PREFERRED_SIZE,189,GroupLayout.PREFERRED_SIZE)).addComponent(label_1)))).addContainerGap(105,Short.MAX_VALUE)));
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(49).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label).addComponent(bookTypeNameText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(18).addComponent(label_1).addGap(10).addComponent(bookTypeDescText,GroupLayout.PREFERRED_SIZE,87,GroupLayout.PREFERRED_SIZE).addGap(41).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(resetBtn).addComponent(addBtn)).addContainerGap()));getContentPane().setLayout(groupLayout);//设置文本域边框
bookTypeDescText.setBorder(newLineBorder(newjava.awt.Color(127,157,185),1,false));}/**
* 添加事件处理
* @param evt
*/privatevoidaddActionPerformed(ActionEvent evt){//获取输入框的值String bookTypeName=bookTypeNameText.getText();String bookTypeDesc=bookTypeDescText.getText();if(bookTypeName==null||"".equals(bookTypeName.trim())){JOptionPane.showMessageDialog(null,"图书类别不能为空!");return;}//新建图书类别实体对象BookType bookType=newBookType(bookTypeName, bookTypeDesc);//定义数据库连接Connection con=null;try{//获取数据库连接
con=DBTool.getConnetion();//初始化图书类别对象BookTypeDao
bookTypeDao=newBookTypeDao();//调用图书类别dao对象的添加方法int res=bookTypeDao.add(con, bookType);if(res!=0){//提示添加成功JOptionPane.showMessageDialog(null,"图书添加成功(n_n)");//清空输入框
bookTypeNameText.setText("");
bookTypeDescText.setText("");}else{//提示添加失败JOptionPane.showMessageDialog(null,"图书添加失败(u_u)");}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("添加图书失败",e);}finally{//关闭数据库DBTool.close(con);}}/**
* 重置事件处理
* @param evt
*/privatevoidresetActionPerformed(ActionEvent evt){//置空图书类别名称输入框
bookTypeNameText.setText("");//置空图书类别描述输入框
bookTypeDescText.setText("");}}
⑤ BookManageInterFrame(图书管理界面)
packagecn.ac.azure.view;importjava.awt.EventQueue;importjava.awt.Font;importjava.sql.Connection;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Vector;importjavax.swing.GroupLayout;importjavax.swing.GroupLayout.Alignment;importjavax.swing.ImageIcon;importjavax.swing.JButton;importjavax.swing.JComboBox;importjavax.swing.JInternalFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JScrollPane;importjavax.swing.JTable;importjavax.swing.JTextField;importjavax.swing.LayoutStyle.ComponentPlacement;importjavax.swing.UIManager;importjavax.swing.border.TitledBorder;importjavax.swing.table.DefaultTableModel;importcn.ac.azure.dao.BookDao;importcn.ac.azure.dao.BookTypeDao;importcn.ac.azure.model.Book;importcn.ac.azure.model.BookType;importcn.ac.azure.util.DBTool;importjavax.swing.JRadioButton;importjavax.swing.ButtonGroup;importjava.awt.event.ActionListener;importjava.awt.event.ActionEvent;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;publicclassBookManageInterFrameextendsJInternalFrame{privateJTextField s_bookNameText;privateJTextField s_authorText;privateJTable bookTable;privateJComboBox s_bookTypecomboBox;privateBookTypeDao bookTypeDao;privateBookDao bookDao;privateJTextField idText;privateJTextField bookNameText;privateJTextField priceText;privateJTextField authorText;privateJTextField bookDescText;privatefinalButtonGroup buttonGroup =newButtonGroup();privateJComboBox bookTypeComboBox;privateJRadioButton maleBtn;privateJRadioButton femaleBtn;/**
* Launch the application.
*/publicstaticvoidmain(String[] args){EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{BookManageInterFrame frame =newBookManageInterFrame();
frame.setVisible(true);}catch(Exception e){
e.printStackTrace();}}});}/**
* Create the frame.
*/publicBookManageInterFrame(){//改变系统默认字体Font font =newFont("Dialog",Font.PLAIN,12);java.util.Enumeration keys =UIManager.getDefaults().keys();while(keys.hasMoreElements()){Object key = keys.nextElement();Object value =UIManager.get(key);if(value instanceofjavax.swing.plaf.FontUIResource){UIManager.put(key, font);}}setIconifiable(true);setClosable(true);setTitle("图书管理 ");setBounds(100,100,767,528);JPanel panel =newJPanel();
panel.setBorder(newTitledBorder(null,"搜索条件",TitledBorder.LEADING,TitledBorder.TOP,null,null));JScrollPane scrollPane =newJScrollPane();JPanel panel_1 =newJPanel();
panel_1.setBorder(newTitledBorder(null,"表单操作",TitledBorder.LEADING,TitledBorder.TOP,null,null));GroupLayout groupLayout =newGroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup().addGap(29).addGroup(groupLayout.createParallelGroup(Alignment.TRAILING).addComponent(panel_1,Alignment.LEADING,GroupLayout.DEFAULT_SIZE,GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addComponent(scrollPane,GroupLayout.DEFAULT_SIZE,661,Short.MAX_VALUE).addComponent(panel,GroupLayout.DEFAULT_SIZE,661,Short.MAX_VALUE)).addGap(38)));
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(29).addComponent(panel,GroupLayout.PREFERRED_SIZE,75,GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(scrollPane,GroupLayout.PREFERRED_SIZE,137,GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(panel_1,GroupLayout.PREFERRED_SIZE,217,GroupLayout.PREFERRED_SIZE).addContainerGap(20,Short.MAX_VALUE)));JLabel label_2 =newJLabel("编号:");
idText =newJTextField();
idText.setColumns(10);JLabel label_3 =newJLabel("图书名称:");
bookNameText =newJTextField();
bookNameText.setColumns(10);JLabel label_4 =newJLabel("作者性别:");
maleBtn =newJRadioButton("男");
buttonGroup.add(maleBtn);
femaleBtn =newJRadioButton("女");
buttonGroup.add(femaleBtn);JLabel label_5 =newJLabel("价格:");
priceText =newJTextField();
priceText.setColumns(10);JLabel label_6 =newJLabel("图书作者:");
authorText =newJTextField();
authorText.setColumns(10);JLabel label_7 =newJLabel("图书类别:");
bookTypeComboBox =newJComboBox();JLabel label_8 =newJLabel("图书描述:");
bookDescText =newJTextField();
bookDescText.setColumns(10);//修改按钮JButton modifyBtn =newJButton("修改");
modifyBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){modifyBookActionPerformed(e);}});
modifyBtn.setIcon(newImageIcon(BookManageInterFrame.class.getResource("/images/modify.png")));//删除按钮JButton deleteBtn =newJButton("删除");
deleteBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){deleteBookActionPerformed(e);}});
deleteBtn.setIcon(newImageIcon(BookManageInterFrame.class.getResource("/images/delete.png")));GroupLayout gl_panel_1 =newGroupLayout(panel_1);
gl_panel_1.setHorizontalGroup(
gl_panel_1.createParallelGroup(Alignment.TRAILING).addGroup(gl_panel_1.createSequentialGroup().addGap(44).addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING,false).addGroup(gl_panel_1.createSequentialGroup().addComponent(label_8).addPreferredGap(ComponentPlacement.RELATED).addComponent(bookDescText)).addGroup(gl_panel_1.createSequentialGroup().addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING).addComponent(label_2).addComponent(label_5)).addPreferredGap(ComponentPlacement.UNRELATED).addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING,false).addComponent(priceText).addComponent(idText,GroupLayout.DEFAULT_SIZE,86,Short.MAX_VALUE)).addGap(37).addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING,false).addGroup(gl_panel_1.createSequentialGroup().addComponent(label_3).addPreferredGap(ComponentPlacement.RELATED).addComponent(bookNameText,GroupLayout.PREFERRED_SIZE,136,GroupLayout.PREFERRED_SIZE)).addGroup(gl_panel_1.createSequentialGroup().addComponent(label_6).addPreferredGap(ComponentPlacement.RELATED).addComponent(authorText))).addGap(35).addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1.createSequentialGroup().addComponent(label_4).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(maleBtn).addGap(18).addComponent(femaleBtn)).addGroup(gl_panel_1.createSequentialGroup().addComponent(label_7).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(bookTypeComboBox,GroupLayout.PREFERRED_SIZE,97,GroupLayout.PREFERRED_SIZE))))).addContainerGap(34,Short.MAX_VALUE)).addGroup(gl_panel_1.createSequentialGroup().addContainerGap(201,Short.MAX_VALUE).addComponent(modifyBtn).addGap(104).addComponent(deleteBtn).addGap(190)));
gl_panel_1.setVerticalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1.createSequentialGroup().addContainerGap().addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(maleBtn).addComponent(bookNameText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(label_3).addComponent(label_2).addComponent(idText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(femaleBtn).addComponent(label_4)).addGap(18).addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(priceText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(label_5).addComponent(label_6).addComponent(authorText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(bookTypeComboBox,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(label_7)).addGap(18).addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(label_8).addComponent(bookDescText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(27).addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(modifyBtn).addComponent(deleteBtn)).addContainerGap()));
panel_1.setLayout(gl_panel_1);//表格
bookTable =newJTable();//表格鼠标按下事件
bookTable.addMouseListener(newMouseAdapter(){@OverridepublicvoidmousePressed(MouseEvent e){tableMousePressed(e);}});
bookTable.setModel(newDefaultTableModel(newObject[][]{},newString[]{"编号","图书名称","图书作者","图书性别","图书价格","图书类别","图书描述"}){boolean[] columnEditables =newboolean[]{false,false,false,false,false,false,false};publicbooleanisCellEditable(int row,int column){return columnEditables[column];}});
bookTable.getColumnModel().getColumn(0).setPreferredWidth(56);
bookTable.getColumnModel().getColumn(1).setPreferredWidth(100);
bookTable.getColumnModel().getColumn(2).setPreferredWidth(63);
bookTable.getColumnModel().getColumn(3).setPreferredWidth(63);
bookTable.getColumnModel().getColumn(4).setPreferredWidth(61);
bookTable.getColumnModel().getColumn(5).setPreferredWidth(94);
bookTable.getColumnModel().getColumn(6).setPreferredWidth(163);
scrollPane.setViewportView(bookTable);JLabel lblL =newJLabel("图书名称:");
s_bookNameText =newJTextField();
s_bookNameText.setColumns(10);JLabel label =newJLabel("图书作者:");
s_authorText =newJTextField();
s_authorText.setColumns(10);JLabel label_1 =newJLabel("图书类别:");
s_bookTypecomboBox =newJComboBox();//图书查询按钮JButton s_searchBtn =newJButton("查询");
s_searchBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){searchActionPerformed(e);}});
s_searchBtn.setIcon(newImageIcon(BookManageInterFrame.class.getResource("/images/search.png")));GroupLayout gl_panel =newGroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addGap(20).addComponent(lblL).addPreferredGap(ComponentPlacement.RELATED).addComponent(s_bookNameText,GroupLayout.PREFERRED_SIZE,88,GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(label).addPreferredGap(ComponentPlacement.RELATED).addComponent(s_authorText,GroupLayout.DEFAULT_SIZE,89,Short.MAX_VALUE).addGap(18).addComponent(label_1).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(s_bookTypecomboBox,GroupLayout.PREFERRED_SIZE,94,GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(s_searchBtn).addGap(29)));
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addContainerGap().addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(lblL).addComponent(s_bookNameText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(label).addComponent(s_authorText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(label_1).addComponent(s_bookTypecomboBox,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(s_searchBtn)).addContainerGap(19,Short.MAX_VALUE)));
panel.setLayout(gl_panel);getContentPane().setLayout(groupLayout);//初始化搜索栏图书类别下拉框fillBookTypeComboBox("search");//初始化操作栏图书类别下拉框fillBookTypeComboBox("modify");//初始化表格显示,显示所有的书籍fillBookTable(newBook());}/**
* 图书修改事件
* @param evt
*/privatevoidmodifyBookActionPerformed(ActionEvent evt){//获取图书idString id=idText.getText();//获取图书名称String bookName=bookNameText.getText();//获取图书作者String author=authorText.getText();//或者作者性别String sex="男";if(femaleBtn.isSelected()){
sex="女";}//获取图书价格String price=priceText.getText();//获取图书idBookType bookType=(BookType)bookTypeComboBox.getSelectedItem();Integer bookTypeId=bookType.getId();//获取图书描述String bookDesc=bookDescText.getText();//判断是否id是否为空if(id==null||"".equals(id)){//为空JOptionPane.showMessageDialog(null,"请选中要删除的行!");//给用户提示return;}//判断图书名称是否为空if(bookName==null||"".equals(bookName)){//为空JOptionPane.showMessageDialog(null,"图书名称不能为空!");//给用户提示return;}//判断图书作者是否为空if(author==null||"".equals(author)){//为空JOptionPane.showMessageDialog(null,"图书作者不能为空!");//给用户提示return;}//判断图书价格是否为空if(price==null||"".equals(price)){//为空JOptionPane.showMessageDialog(null,"图书价格不能为空!");//给用户提示return;}//从获取的图书信息创建图书对象Book book=newBook(Integer.parseInt(id),bookName, author, sex,Float.parseFloat(price), bookTypeId, bookDesc,null);System.out.println("从获取的图书信息创建图书对象:"+book);//定义数据库连接Connection con=null;try{//获取数据库连接
con=DBTool.getConnetion();//初始化图书数据访问对象
bookDao=newBookDao();//执行图书访问对象的修改方法,并获得修改的记录数int res=bookDao.update(con, book);if(res==1){//为1JOptionPane.showMessageDialog(null,"图书修改成功n_n");//刷新图书表格显示fillBookTable(newBook());//重置操作栏resetValue();}else{//为0JOptionPane.showMessageDialog(null,"图书修改失败u_u");}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("修改图书失败",e);}finally{//关闭数据库连接DBTool.close(con);}}/**
* 图书删除事件
* @param evt
*/privatevoiddeleteBookActionPerformed(ActionEvent evt){//获取图书idString id=idText.getText();//判断是否id是否为空if(id==null||"".equals(id)){//为空JOptionPane.showMessageDialog(null,"请选中要删除的行!");//给用户提示return;}//定义数据库连接对象Connection con=null;try{//初始化数据库连接对象
con=DBTool.getConnetion();//初始化图书数据访问对象
bookDao=newBookDao();//执行图书访问对象的删除方法并返回删除的记录数int res=bookDao.delete(con,Integer.parseInt(id));if(res==1){//为1JOptionPane.showMessageDialog(null,"图书删除成功n_n");//刷新图书表格显示fillBookTable(newBook());//重置操作栏resetValue();}else{//为其他JOptionPane.showMessageDialog(null,"图书删除失败u_u");}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("删除图书失败",e);}finally{//记得关闭数据库(******)DBTool.close(con);}}/**
* 重置操作栏的所有值
*/privatevoidresetValue(){
idText.setText("");
bookNameText.setText("");
authorText.setText("");
maleBtn.setSelected(true);
priceText.setText("");fillBookTypeComboBox("modify");
bookDescText.setText("");}/**
* 表格鼠标按下事件处理
* @param evt
*/privatevoidtableMousePressed(MouseEvent evt){//获取图书表格选中的行的行号int row=bookTable.getSelectedRow();//获取选中行第一个数据并设置显示在操作栏的id框
idText.setText((Integer)bookTable.getValueAt(row,0)+"");//获取选中行第二个数据并设置显示在操作栏的图书名称框
bookNameText.setText((String)bookTable.getValueAt(row,1));//获取选中行第三个数据并设置显示在操作栏的图书作者框
authorText.setText((String)bookTable.getValueAt(row,2));//获取选中行第四个数据并设置显示在操作栏的作者性别单选框String sex=(String)bookTable.getValueAt(row,3);if("男".equals(sex)){
maleBtn.setSelected(true);}else{
femaleBtn.setSelected(true);}//获取选中行第五个数据并设置显示在操作栏的图书价格框
priceText.setText((Float)bookTable.getValueAt(row,4)+"");//获取选中行第六个数据并设置显示在操作栏的图书类别下拉框中String bookTypeName=(String)bookTable.getValueAt(row,5);int rows=bookTypeComboBox.getItemCount();//获取下拉框总共的选项for(int i=0;i<rows;i++){//遍历下拉框BookType item=(BookType) bookTypeComboBox.getItemAt(i);//获取每一个选项并强转图书类别对象if(item.getBookTypeName().equals(bookTypeName)){//将获取的图书类别和下拉框中的图书类别比较,若相同
bookTypeComboBox.setSelectedIndex(i);//则该下拉框选项被选中}}//获取选中行第七个数据并设置显示在操作栏的图书描述框
bookDescText.setText((String)bookTable.getValueAt(row,6));}/**
* 图书查询事件处理
* @param evt 事件对象
*/privatevoidsearchActionPerformed(ActionEvent evt){//获取查询的条件String bookName=s_bookNameText.getText();//图书名称String author=s_authorText.getText();//图书作者String bookTypeName=s_bookTypecomboBox.getSelectedItem().toString();//图书类别//对图书类别"请选择..."换成""if("请选择...".equals(bookTypeName)){
bookTypeName="";}//生成带有条件的图书对象Book book=newBook();
book.setBookName(bookName);//设置图书名称条件
book.setAuthor(author);//设置图书作者条件
book.setBookTypeName(bookTypeName);//设置图书类别条件//调用table填充函数,根据查询结果重新填充表格fillBookTable(book);}/**
* 初始化图书类别下拉框
* @param type 根据不同的参数填充不同的下拉框
*/privatevoidfillBookTypeComboBox(String type){//定义一个图书类别,用于存储查询的图书类别BookType s_bookType=null;//定义一个数据库连接Connection con=null;try{//获取数据库连接
con=DBTool.getConnetion();//初始化图书类别访问数据对象
bookTypeDao=newBookTypeDao();//查询图书类别,得到结果集ResultSet rs=bookTypeDao.search(con,newBookType());if("search".equals(type)){BookType bookType=newBookType();
bookType.setBookTypeName("请选择...");
bookType.setId(-1);
s_bookTypecomboBox.addItem(bookType);}//遍历结果集while(rs.next()){//如果有数据的话//初始化接受查询的图书类别
s_bookType=newBookType();//根据查询结果设置id
s_bookType.setId(rs.getInt("id"));//根据查询结果设置图书类别名称
s_bookType.setBookTypeName(rs.getString("bookTypeName"));if("search".equals(type)){//将查询的图书类别添加到下拉框中
s_bookTypecomboBox.addItem(s_bookType);}if("modify".equals(type)){//将查询的图书类别添加到表单操作下拉框中
bookTypeComboBox.addItem(s_bookType);}}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("初始化下拉框失败",e);}finally{//关闭数据库连接DBTool.close(con);}}/**
* 初始化表格,列出所有的书籍
* @param book
*/privatevoidfillBookTable(Book book){//获取表格的模型DefaultTableModel dtm=(DefaultTableModel) bookTable.getModel();//填充表格时设置成0行(相当于归零处理)
dtm.setRowCount(0);//定义数据库连接Connection con=null;try{//获取数据库连接
con=DBTool.getConnetion();//初始化图书数据访问对象
bookDao=newBookDao();//按条件查询图书(这里没有条件,查出所有书籍)ResultSet rs=bookDao.search(con, book);//遍历查询结果while(rs.next()){//定义一个集合,由于存储图书信息Vector v=newVector();
v.add(rs.getInt("id"));//添加编号
v.add(rs.getString("bookName"));//添加图书名称
v.add(rs.getString("author"));//添加图书作者
v.add(rs.getString("sex"));//添加作者性别
v.add(rs.getFloat("price"));//添加图书价格
v.add(rs.getString("bookTypeName"));//添加图书类别
v.add(rs.getString("bookDesc"));//添加表格新行
dtm.addRow(v);}}catch(SQLException e){//记录日志
e.printStackTrace();thrownewRuntimeException("初始化表格失败",e);}finally{//关闭数据库连接DBTool.close(con);}}}
⑥ BookAddInterFrame(图书添加界面)
packagecn.ac.azure.view;importjava.awt.EventQueue;importjava.awt.Font;importjava.sql.Connection;importjava.sql.ResultSet;importjava.sql.SQLException;importjavax.swing.ButtonGroup;importjavax.swing.GroupLayout;importjavax.swing.GroupLayout.Alignment;importjavax.swing.ImageIcon;importjavax.swing.JButton;importjavax.swing.JComboBox;importjavax.swing.JInternalFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JRadioButton;importjavax.swing.JTextArea;importjavax.swing.JTextField;importjavax.swing.UIManager;importjavax.swing.LayoutStyle.ComponentPlacement;importjavax.swing.border.LineBorder;importcn.ac.azure.dao.BookDao;importcn.ac.azure.dao.BookTypeDao;importcn.ac.azure.model.Book;importcn.ac.azure.model.BookType;importcn.ac.azure.util.DBTool;importjava.awt.event.ActionListener;importjava.awt.event.ActionEvent;publicclassBookAddInterFrameextendsJInternalFrame{privateJTextField bookNameText;privateJTextField authorText;privatefinalButtonGroup buttonGroup =newButtonGroup();privateJTextField priceText;privateJComboBox bookTypeComboBox;privateJRadioButton maleBtn;privateJRadioButton femaleBtn;privateJTextArea bookDescText;privateBookTypeDao bookTypeDao;privateBookDao bookDao;/**
* Launch the application.
*/publicstaticvoidmain(String[] args){EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{BookAddInterFrame frame =newBookAddInterFrame();
frame.setVisible(true);}catch(Exception e){
e.printStackTrace();}}});}/**
* Create the frame.
*/publicBookAddInterFrame(){setIconifiable(true);setClosable(true);// 改变系统默认字体Font font =newFont("Dialog",Font.PLAIN,12);java.util.Enumeration keys =UIManager.getDefaults().keys();while(keys.hasMoreElements()){Object key = keys.nextElement();Object value =UIManager.get(key);if(value instanceofjavax.swing.plaf.FontUIResource){UIManager.put(key, font);}}setTitle("图书添加 ");setBounds(100,100,699,449);JLabel label =newJLabel("图书名称:");
bookNameText =newJTextField();
bookNameText.setColumns(10);JLabel label_1 =newJLabel("图书作者:");
authorText =newJTextField();
authorText.setColumns(10);JLabel label_2 =newJLabel("作者性别:");
maleBtn =newJRadioButton("男");
buttonGroup.add(maleBtn);
femaleBtn =newJRadioButton("女");
buttonGroup.add(femaleBtn);JLabel label_3 =newJLabel("图书价格:");
priceText =newJTextField();
priceText.setColumns(10);JLabel label_4 =newJLabel("图书类别:");// 图书类别下拉框
bookTypeComboBox =newJComboBox();JLabel label_5 =newJLabel("图书描述:");
bookDescText =newJTextArea();// 图书添加按钮JButton addBtn =newJButton("添加");
addBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){// 图书添加按钮事件处理bookAddActionPerformed(e);}});
addBtn.setIcon(newImageIcon(BookAddInterFrame.class.getResource("/images/add.png")));// 图书重置按钮JButton resetBtn =newJButton("重置");
resetBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e){bookResetActionPerformed(e);}});
resetBtn.setIcon(newImageIcon(BookAddInterFrame.class.getResource("/images/reset.png")));GroupLayout groupLayout =newGroupLayout(getContentPane());
groupLayout
.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(38).addGroup(groupLayout
.createParallelGroup(Alignment.LEADING).addGroup(
groupLayout.createSequentialGroup().addGap(6).addGroup(groupLayout
.createParallelGroup(Alignment.LEADING,false).addGroup(groupLayout.createSequentialGroup().addGroup(groupLayout
.createParallelGroup(Alignment.LEADING,false).addGroup(groupLayout.createSequentialGroup().addComponent(label_4).addPreferredGap(ComponentPlacement.RELATED).addComponent(bookTypeComboBox,0,GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)).addGroup(groupLayout.createSequentialGroup().addComponent(label).addPreferredGap(ComponentPlacement.RELATED).addComponent(bookNameText,GroupLayout.PREFERRED_SIZE,116,GroupLayout.PREFERRED_SIZE)).addGroup(groupLayout.createSequentialGroup().addComponent(label_2).addPreferredGap(ComponentPlacement.RELATED).addComponent(maleBtn).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(femaleBtn))).addGap(44).addGroup(groupLayout
.createParallelGroup(Alignment.LEADING,false).addGroup(groupLayout.createSequentialGroup().addComponent(label_3).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(priceText)).addGroup(groupLayout.createSequentialGroup().addComponent(label_1).addPreferredGap(ComponentPlacement.RELATED).addComponent(authorText,GroupLayout.PREFERRED_SIZE,128,GroupLayout.PREFERRED_SIZE)))).addGroup(groupLayout.createSequentialGroup().addComponent(label_5).addPreferredGap(ComponentPlacement.RELATED).addComponent(bookDescText))).addPreferredGap(ComponentPlacement.RELATED,164,Short.MAX_VALUE)).addGroup(groupLayout.createSequentialGroup().addGap(94).addComponent(addBtn).addGap(96).addComponent(resetBtn))).addContainerGap()));
groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(32).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label).addComponent(bookNameText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE).addComponent(label_1).addComponent(authorText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(31).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_2).addComponent(maleBtn).addComponent(femaleBtn).addComponent(label_3).addComponent(
priceText,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(37).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_4).addComponent(bookTypeComboBox,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)).addGap(30).addGroup(
groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_5).addComponent(
bookDescText,GroupLayout.PREFERRED_SIZE,102,GroupLayout.PREFERRED_SIZE)).addGap(38).addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(addBtn).addComponent(resetBtn)).addContainerGap(45,Short.MAX_VALUE)));getContentPane().setLayout(groupLayout);// 设置文本域边框
bookDescText.setBorder(newLineBorder(newjava.awt.Color(127,157,185),1,false));// 在构造函数中调用图书类别下拉框初始化方法fillBookTypeName();// 在构造函数中初始化性别。默认为男
maleBtn.setSelected(true);}/**
* 重置按钮事件处理
*
* @param evt
* 重置按钮事件对象
*/privatevoidbookResetActionPerformed(ActionEvent evt){reset();}/**
* 图书添加界面信息重置
*/privatevoidreset(){
bookNameText.setText("");
authorText.setText("");
maleBtn.setSelected(true);
priceText.setText("");
bookTypeComboBox.setSelectedIndex(0);
bookDescText.setText("");}/**
* 图书添加按钮事件处理
*
* @param evt
* 添加事件对象
*/privatevoidbookAddActionPerformed(ActionEvent evt){String bookName = bookNameText.getText();// 获取图书名称if(bookName ==null||"".equals(bookName.trim())){JOptionPane.showMessageDialog(null,"图书名称不能为空!");return;}String author = authorText.getText();// 获取图书作者String sex =null;// 获取图书作者性别if(maleBtn.isSelected()){
sex ="男";}else{
sex ="女";}String prices = priceText.getText();// 获取图书价格if(prices ==null||"".equals(prices.trim())){JOptionPane.showMessageDialog(null,"图书价格不能为空!");return;}float price =Float.parseFloat(prices);BookType bookType =(BookType) bookTypeComboBox.getSelectedItem();// 获取图书类别int bookTypeId = bookType.getId();// 获取图书类别idSystem.out.println("ID="+bookTypeId);String bookDesc = bookDescText.getText();// 获取图书描述// 根据获取的添加图书界面获取的信息创建图书对象Book book =newBook(null, bookName, author, sex, price, bookTypeId, bookName, bookDesc);System.out.println("实体类:"+book);// 定义数据库连接Connection con =null;try{// 获取数据库连接
con =DBTool.getConnetion();// 初始化图书数据访问对象
bookDao =newBookDao();// 调用添加方法,向数据库添加书籍System.out.println("5555"+book);int num = bookDao.add(con, book);// 根据返回值判断图书是否添加成功if(num >0){JOptionPane.showMessageDialog(null,"图书添加成功n_n");// 添加成功之后重置界面reset();}else{JOptionPane.showMessageDialog(null,"图书添加成功u_u");}}catch(SQLException e){// 记录日志
e.printStackTrace();thrownewRuntimeException("添加图书失败", e);}finally{// 关闭数据库连接DBTool.close(con);}}// 填充图书类别名称privatevoidfillBookTypeName(){// 定义数据库连接对象Connection con =null;// 定义图书类别,用于查询和储存查询的书籍BookType bookType =null;try{// 获取数据库连接
con =DBTool.getConnetion();// 初始化图书类别访问对象
bookTypeDao =newBookTypeDao();// 查询t_bookType中含有的图书类别ResultSet rs = bookTypeDao.search(con, bookType);// 遍历查询结果while(rs.next()){// 出事化图书类别
bookType =newBookType();// 设置图书的id
bookType.setId(rs.getInt("id"));// 设置图书的名称
bookType.setBookTypeName(rs.getString("bookTypeName"));// 将图书类别对象添加到下拉框中(这里添加对象,便于获得id)
bookTypeComboBox.addItem(bookType.getBookTypeName());}}catch(SQLException e){// 记录日志
e.printStackTrace();thrownewRuntimeException("初始化列表失败", e);}finally{// 关闭数据路连接DBTool.close(con);}}}
⑦ LibraryInterFrame(关于我们界面)
packagecn.ac.azure.view;importjava.awt.EventQueue;importjavax.swing.JInternalFrame;importjavax.swing.GroupLayout;importjavax.swing.GroupLayout.Alignment;importjavax.swing.JLabel;importjavax.swing.UIManager;importjavax.swing.ImageIcon;importjava.awt.Font;importjava.awt.Color;publicclassLibraryInterFrameextendsJInternalFrame{privatestaticfinallong serialVersionUID =1L;/**
* Launch the application.
*/publicstaticvoidmain(String[] args){EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{LibraryInterFrame frame =newLibraryInterFrame();
frame.setVisible(true);}catch(Exception e){
e.printStackTrace();}}});}/**
* Create the frame.
*/publicLibraryInterFrame(){//改变系统默认字体Font font =newFont("Dialog",Font.PLAIN,12);java.util.Enumeration<Object> keys =UIManager.getDefaults().keys();while(keys.hasMoreElements()){Object key = keys.nextElement();Object value =UIManager.get(key);if(value instanceofjavax.swing.plaf.FontUIResource){UIManager.put(key, font);}}setClosable(true);setIconifiable(true);setBounds(450,150,503,300);JLabel label =newJLabel("");
label.setIcon(newImageIcon(LibraryInterFrame.class.getResource("/images/library.png")));JLabel label_1 =newJLabel("欢迎使用图书管理系统");
label_1.setForeground(Color.GREEN);
label_1.setBackground(Color.GREEN);
label_1.setFont(newFont("宋体",Font.PLAIN,20));GroupLayout groupLayout =newGroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addContainerGap(140,Short.MAX_VALUE).addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup().addComponent(label).addGap(175)).addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup().addComponent(label_1).addGap(137)))));
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout.createSequentialGroup().addGap(39).addComponent(label).addGap(28).addComponent(label_1).addContainerGap(51,Short.MAX_VALUE)));getContentPane().setLayout(groupLayout);}}
5、数据库【db_book】
/*
Navicat Premium Data Transfer
Source Server : 127.0.0.1
Source Server Type : MySQL
Source Server Version : 50733
Source Host : localhost:3306
Source Schema : db_book
Target Server Type : MySQL
Target Server Version : 50733
File Encoding : 65001
Date: 19/07/2021 17:34:44
*/SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS =0;-- ------------------------------ Table structure for t_book-- ----------------------------DROPTABLEIFEXISTS`t_book`;CREATETABLE`t_book`(`id`int(50)NOTNULLAUTO_INCREMENT,`bookName`varchar(50)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,`author`varchar(50)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,`sex`varchar(50)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,`price`double(50,2)NULLDEFAULTNULL,`bookTypeId`int(50)NULLDEFAULTNULL,`bookTypeName`varchar(50)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,`bookDesc`varchar(5000)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,PRIMARYKEY(`id`)USINGBTREE,INDEX`fk_booktype`(`bookTypeId`)USINGBTREE,CONSTRAINT`fk_booktype`FOREIGNKEY(`bookTypeId`)REFERENCES`t_booktype`(`id`)ONDELETESETNULLONUPDATESETNULL)ENGINE=InnoDBAUTO_INCREMENT=6CHARACTERSET= utf8 COLLATE= utf8_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of t_book-- ----------------------------INSERTINTO`t_book`VALUES(1,'《人间失格》','(日)太宰治','男',66.00,1,'小说','(日本小说家太宰治代表作,一个对村上春树影响至深的绝望凄美故事)');INSERTINTO`t_book`VALUES(2,'《三体》','刘慈欣','女',55.80,1,'小说','刘慈欣代表作,亚洲首部“雨果奖”获奖作品!\r\n《三体》第73届世界科幻雨果奖获奖作品,银河奖特别奖,《三体3》轨迹奖长篇科幻小说!2017年世界雨果奖提名作品。');INSERTINTO`t_book`VALUES(3,'《人生海海》','麦家','男',55.00,2,'文化科学','麦家重磅力作,莫言、董卿盛赞,连续两年高居各大畅销榜,发行量超180万册,罗一舟同款书)\r\n上校赢了所有的仗,却败给一个不足道的秘密。茅盾文学奖得主麦家暌违8年,打磨5年,挑战常人不敢落笔之处,解密人性的荒唐与高尚。人生海海,何必在意一时沉浮!');INSERTINTO`t_book`VALUES(4,'《大国崛起》','唐晋','男',50.40,2,'历史','以历史的眼光和全球的视野解读15世纪以来9个世界性大国崛起的历史,中国能否成为第十个崛起的大国?');INSERTINTO`t_book`VALUES(5,'《中华人民共和国民法典》','法律出版社','男',8.10,2,'哲学、社会','民法典是新中国首部以“法典”命名的法律,是新时代我国社会主义法治建设的重大成果,是为百姓生活量身定制的权利宝典。自2021年1月1日起施行。');-- ------------------------------ Table structure for t_booktype-- ----------------------------DROPTABLEIFEXISTS`t_booktype`;CREATETABLE`t_booktype`(`id`int(50)NOTNULLAUTO_INCREMENT,`bookTypeName`varchar(500)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,`bookTypeDesc`varchar(500)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBAUTO_INCREMENT=25CHARACTERSET= utf8 COLLATE= utf8_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of t_booktype-- ----------------------------INSERTINTO`t_booktype`VALUES(1,'A 马克思主义、列宁主义、毛泽东思想、邓小平理论','A 马克思主义、列宁主义、毛泽东思想、邓小平理论');INSERTINTO`t_booktype`VALUES(2,'B 哲学、宗教','B 哲学、宗教');INSERTINTO`t_booktype`VALUES(3,'C 社会科学总论','C 社会科学总论');INSERTINTO`t_booktype`VALUES(4,'D 政治、法律','D 政治、法律');INSERTINTO`t_booktype`VALUES(5,'F 经济','F 经济');INSERTINTO`t_booktype`VALUES(6,'G 文化、科学、教育、体育','G 文化、科学、教育、体育');INSERTINTO`t_booktype`VALUES(7,'H 语言、文字','H 语言、文字');INSERTINTO`t_booktype`VALUES(8,'I 文学','I 文学');INSERTINTO`t_booktype`VALUES(9,'J 艺术','J 艺术');INSERTINTO`t_booktype`VALUES(10,'K 历史、地理','K 历史、地理');INSERTINTO`t_booktype`VALUES(11,'N 自然科学总论','N 自然科学总论');INSERTINTO`t_booktype`VALUES(12,'O 数理科学和化学','O 数理科学和化学');INSERTINTO`t_booktype`VALUES(13,'Q 生物科学','Q 生物科学');INSERTINTO`t_booktype`VALUES(14,'R 医药、卫生 ','R 医药、卫生');INSERTINTO`t_booktype`VALUES(15,'S 农业科学','S 农业科学');INSERTINTO`t_booktype`VALUES(16,'T-TN 工业技术','T-TN 工业技术');INSERTINTO`t_booktype`VALUES(17,'TP 自动化技术、计算机技术','TP 自动化技术、计算机技术');INSERTINTO`t_booktype`VALUES(18,'TQ 化学工业','TQ 化学工业');INSERTINTO`t_booktype`VALUES(19,'TU 建筑科学','TU 建筑科学');INSERTINTO`t_booktype`VALUES(20,'TV 水利工程','TV 水利工程');INSERTINTO`t_booktype`VALUES(21,'U 交通运输','U 交通运输');INSERTINTO`t_booktype`VALUES(22,'V 航空、航天','V 航空、航天');INSERTINTO`t_booktype`VALUES(23,'X 环境科学、安全科学','X 环境科学、安全科学');INSERTINTO`t_booktype`VALUES(24,'Z 综合性图书','Z 综合性图书');-- ------------------------------ Table structure for t_user-- ----------------------------DROPTABLEIFEXISTS`t_user`;CREATETABLE`t_user`(`id`int(50)NOTNULLAUTO_INCREMENT,`username`varchar(50)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,`password`varchar(50)CHARACTERSET utf8 COLLATE utf8_general_ci NULLDEFAULTNULL,PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBAUTO_INCREMENT=2CHARACTERSET= utf8 COLLATE= utf8_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of t_user-- ----------------------------INSERTINTO`t_user`VALUES(1,'11','123456');SET FOREIGN_KEY_CHECKS =1;
三、项目地址:
CSDN赞助下载:
版权归原作者 明金同学 所有, 如有侵权,请联系我们删除。