Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
用java做图书管理系统_eclipse java,希望能够帮助你!!!。
本项目为Java swing项目,在工作环境中基本使用不到,但是很多学校把这个当做编程入门的项目来做,故分享出本项目供初学者参考。
CSDN赞助下载:https://download.csdn.net/download/weixin_/
①基本数据维护:
图书类别管理 >> 图书类别添加、图书类别维护
图书管理 >> 图书添加、图书维护
②关于我们
可全部缩小到左下角
package cn.ac.azure.util; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * 数据库连接工具类 * @author 明金同学 * */ public class DBTool {
private static String driver; //数据库驱动 private static String url; //数据库连接地址 private static String user; //数据库连接用户 private static String password; //数据库连接密码 static{
//新建一个properties,用于读取db.properties配置文件 Properties p=new Properties(); //新建一个字符串,保存配置文件的路径 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(); throw new RuntimeException("加载驱动失败",e); } } catch (IOException e) {
e.printStackTrace(); throw new RuntimeException("找不到配置文件",e); } } /** * 获取数据库连接 * @return 数据库连接对象 * @throws SQLException 提醒调用者捕获异常,并在finally中关闭关闭异常 */ public static Connection getConnetion() throws SQLException{
//通过DriverManager获得数据库连接 return DriverManager.getConnection(url, user, password); } /** * 关闭数据库连接 * @param con */ public static void close(Connection con){
if(con!=null){
//如果数据连接不为空 try {
//关闭数据库连接 con.close(); } catch (SQLException e) {
e.printStackTrace(); throw new RuntimeException("数据库关闭失败",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); // } // } }
package cn.ac.azure.model; /** * 图书实体 * @author 明金同学 * */ public class Book {
private Integer id; //图书id private String bookName; //图书名称 private String author; //图书作者 private String sex; //作者性别 private Float price; //图书价格 private Integer bookTypeId; //图书类别ID private String bookTypeName; //图书类别名称 private String bookDesc; //图书描述 public Book() {
super(); } public Book(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; } public Integer getId() {
return id; } public void setId(Integer id) {
this.id = id; } public String getBookName() {
return bookName; } public void setBookName(String bookName) {
this.bookName = bookName; } public String getAuthor() {
return author; } public void setAuthor(String author) {
this.author = author; } public String getSex() {
return sex; } public void setSex(String sex) {
this.sex = sex; } public Float getPrice() {
return price; } public void setPrice(Float price) {
this.price = price; } public Integer getBookTypeId() {
return bookTypeId; } public void setBookTypeId(Integer bookTypeId) {
this.bookTypeId = bookTypeId; } public String getBookTypeName() {
return bookTypeName; } public void setBookTypeName(String bookTypeName) {
this.bookTypeName = bookTypeName; } public String getBookDesc() {
return bookDesc; } public void setBookDesc(String bookDesc) {
this.bookDesc = bookDesc; } @Override public String toString() {
return "Book [测试=" + id + ", bookName=" + bookName + ", author=" + author + ", sex=" + sex + ", price=" + price + ", bookTypeId=" + bookTypeId + ", bookTypeName=" + bookTypeName + ", bookDesc=" + bookDesc + "]"; } }
package cn.ac.azure.model; /** * 图书类别实体 * @author 明金同学 * */ public class BookType {
private int id; //定义ID private String bookTypeName; //定义图书类别名称 private String bookTypeDesc; //定义图书类别描述 //无参构造器 public BookType() {
} //有参构造函数 public BookType(String bookTypeName, String bookTypeDesc) {
super(); this.bookTypeName = bookTypeName; this.bookTypeDesc = bookTypeDesc; } public BookType(int id, String bookTypeName, String bookTypeDesc) {
super(); this.id = id; this.bookTypeName = bookTypeName; this.bookTypeDesc = bookTypeDesc; } public int getId() {
return id; } public void setId(int id) {
this.id = id; } public String getBookTypeName() {
return bookTypeName; } public void setBookTypeName(String bookTypeName) {
this.bookTypeName = bookTypeName; } public String getBookTypeDesc() {
return bookTypeDesc; } public void setBookTypeDesc(String bookTypeDesc) {
this.bookTypeDesc = bookTypeDesc; } @Override public String toString() {
return "BookType [id=" + id + ", bookTypeName=" + bookTypeName + ", bookTypeDesc=" + bookTypeDesc + "]"; } }
package cn.ac.azure.model; /** * 用户实体 * @author 明金同学 * */ public class User {
private int id; //用户id private String username; //用户名称 private String password; //用户密码 public User() {
} @Override public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]"; } public User(String username, String password) {
super(); this.username = username; this.password = password; } public int getId() {
return id; } public void setId(int id) {
this.id = id; } public String getUsername() {
return username; } public void setUsername(String username) {
this.username = username; } public String getPassword() {
return password; } public void setPassword(String password) {
this.password = password; } }
package cn.ac.azure.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import cn.ac.azure.model.Book; /** * 图书dao类 * @author 明金同学 * */ public class BookDao {
/** * 图书添加 * @param con 数据库库连接对象 * @param book 添加的图书对象 * @return 返回添加操作的数据库记录数 * @throws SQLException 抛出数据库异常 */ public int add(Connection con,Book book) throws SQLException{
//拼写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); //获得预编译对象ps PreparedStatement 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 抛出数据库异常 */ public ResultSet search(Connection con,Book book) throws SQLException{
//定义图书名称 String bookName=null; //定义图书作者 String author=null; //定义图书类别名称 String bookTypeName=null; //如果图书不为空的话,就为前三个字段赋值,按照条件查询 if(book!=null){
bookName=book.getBookName(); author=book.getAuthor(); bookTypeName=book.getBookTypeName(); } //定义一个字符串缓冲对象类存储查询添加 StringBuilder sb=new StringBuilder("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 抛出数据库异常,同时提醒调用者关闭数据库 */ public int update(Connection con,Book book) throws SQLException{
//编写sql语句 String sql="update t_book set bookName=?,author=?,sex=?," + "price=?,bookTypeId=?,bookDesc=? where id=?"; //获取预编译对象ps PreparedStatement 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 抛出数据库异常,同时提醒调用者关闭数据库 */ public int delete(Connection con,int id) throws SQLException{
//编写sql语句 String sql="delete from t_book where id=?"; //获取预编译对象ps PreparedStatement ps=con.prepareStatement(sql); //设置ps参数 ps.setInt(1, id); //执行DML删除语句并返回删除的记录数 return ps.executeUpdate(); } }
package cn.ac.azure.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import cn.ac.azure.model.BookType; /** * 图书类别dao类 * @author 明金同学 * */ public class BookTypeDao {
/** * 图书类别添加 * @param con 数据库连接对象 * @param bookType 要添加的图书类别 * @return 返回数据库操作的记录数 * @throws SQLException */ public int add(Connection con,BookType bookType) throws SQLException{
//拼写sql插入语句 String sql="insert into t_bookType values(null,?,?)"; //创建预编译对象ps PreparedStatement 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 抛出数据库异常 */ public ResultSet search(Connection con,BookType bookType) throws SQLException{
/* * 思路:当jdbc查询数据库有多个条件从外部输入时,这是最好创建一个字符串缓冲类来添加条件到sql语句中。 * 同时,不知道有哪些条件是第一条件,无法确定where关键字的所在,于是添加条件都用(and 条件) * 最后字符串转换成字符串时在将第一个and替换成where */ //定义一个图书类别名称 String bookTypeName=null; if(bookType!=null){
//如果类别对象不为空的话,就获取它的类别名称 bookTypeName=bookType.getBookTypeName(); } //创建一个字符串缓冲类 StringBuilder sb=new StringBuilder("select * from t_bookType"); //添加查询语句的条件(and + 条件) if(!(bookTypeName==null || "".equals(bookTypeName.trim()))){
//jdbc中,数据库字符串要用单引号括起来 sb.append(" and bookTypeName like '%"+bookType.getBookTypeName()+"%'"); } //将字符串缓冲对象转换成字符串,同时把第一个and替换成where String sql=sb.toString().replaceFirst("and", "where"); //获取预编译对象 PreparedStatement ps=con.prepareStatement(sql); //返回ps执行查询之后的结果集 return ps.executeQuery(); } /** * 图书类别修改 * @param con 数据路连接对象 * @param bookType 要修改的图书类别 * @return 返回数据库更新的记录数 * @throws SQLException 抛出数据库异常 */ public int update(Connection con,BookType bookType) throws SQLException{
//拼写sql更新语句 String sql="update t_bookType set bookTypeName=? , bookTypeDesc=? where id=?"; //获取预编译对象ps PreparedStatement 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 抛出数据库异常 */ public int delete(Connection con,String id) throws SQLException{
//拼写sql删除语句 String sql="delete from t_bookType where id=?"; //获取预编译对象ps PreparedStatement ps=con.prepareStatement(sql); //设置ps参数 ps.setString(1, id); //执行ps更行操作,并返回改变的数据记录条数 return ps.executeUpdate(); } }
package cn.ac.azure.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import cn.ac.azure.model.User; /** * 用户数据访问对象 * @author 明金同学 * */ public class UserDao {
/** * 登录验证 * @param con 数据库连接对象 * @param user 登录的账户 * @return 返回一个用户对象,为null,则登录失败;反之,则登录成功 * @throws Exception 让调用者处理异常 */ public User login(Connection con,User user) throws SQLException{
//定义一个返回用户对象 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=new User(); resultUser.setId(rs.getInt("id")); //设置用户id resultUser.setUsername(rs.getString("username")); //设置用户名称 resultUser.setPassword(rs.getString("password")); //设置用户密码 } //返回用户对象 return resultUser; } }
package cn.ac.azure.view; import java.awt.EventQueue; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.SQLException; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; 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.LayoutStyle.ComponentPlacement; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.EmptyBorder; import cn.ac.azure.dao.UserDao; import cn.ac.azure.model.User; import cn.ac.azure.util.DBTool; public class LoginFrame extends JFrame {
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(); } } private JPanel contentPane; private JTextField usernameText; private JPasswordField passwordText; private JButton loginBtn; private JButton resetBtn; /** * Launch the application. */ public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginFrame frame = new LoginFrame(); frame.setVisible(true); } catch (Exception e) {
e.printStackTrace(); } } }); } /** * Create the frame. */ public LoginFrame() {
//改变系统默认字体 Font font = new Font("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 instanceof javax.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 = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JLabel lblNewLabel = new JLabel("\u56FE\u4E66\u7BA1\u7406\u7CFB\u7EDF"); lblNewLabel.setFont(new Font("宋体", Font.BOLD, 22)); lblNewLabel.setIcon(new ImageIcon(LoginFrame.class.getResource("/images/logo.png"))); JLabel lblNewLabel_1 = new JLabel("用户名 :"); lblNewLabel_1.setIcon(new ImageIcon(LoginFrame.class.getResource("/images/userName.png"))); usernameText = new JTextField(); usernameText.setColumns(10); JLabel lblNewLabel_2 = new JLabel("密 码 :"); lblNewLabel_2.setIcon(new ImageIcon(LoginFrame.class.getResource("/images/password.png"))); passwordText = new JPasswordField(); //添加登陆按钮 loginBtn = new JButton("登录"); loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loginActionPerformed(e); } }); loginBtn.setIcon(new ImageIcon(LoginFrame.class.getResource("/images/login.png"))); //添加重置按钮 resetBtn = new JButton("重置"); resetBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resetActionPerformed(e); } }); resetBtn.setIcon(new ImageIcon(LoginFrame.class.getResource("/images/reset.png"))); GroupLayout gl_contentPane = new GroupLayout(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 */ private void loginActionPerformed(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=new User(username, password); //定义数据库连接 Connection con=null; try {
//利用数据库工具类获取数据库连接 con=DBTool.getConnetion(); //新建一个用户数据访问对象 UserDao userDao=new UserDao(); //调用其登录验证方法获取一个用户对象 User currUser=userDao.login(con, user); //判断返回的用户对象 if(currUser!=null){
//不为空,表示登录成功 //进入主界面,并设置可见 new MainFrame().setVisible(true); //释放当前窗口资源 dispose(); }else{
//为空,表示登录不成功 JOptionPane.showMessageDialog(null, "登录失败(u_u)"); } } catch (SQLException e) {
e.printStackTrace(); throw new RuntimeException("登录失败",e); }finally{
//关闭数据库连接 DBTool.close(con); } } /** * 重置事件处理 * @param evt */ private void resetActionPerformed(ActionEvent evt) {
usernameText.setText(""); passwordText.setText(""); } }
package cn.ac.azure.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import javax.swing.ImageIcon; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.EmptyBorder; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class MainFrame extends JFrame {
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(); } } private static final long serialVersionUID = 1L; //定义内容窗格 private JPanel contentPane; //定义桌面窗格 private JDesktopPane table; /** * Launch the application. */ public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame(); frame.setVisible(true); } catch (Exception e) {
e.printStackTrace(); } } }); } /** * Create the frame. */ public MainFrame() {
//改变系统默认字体 Font font = new Font("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 instanceof javax.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 = new JMenuBar(); menuBar.setToolTipText(""); setJMenuBar(menuBar); JMenu menu = new JMenu("\u57FA\u672C\u6570\u636E\u7EF4\u62A4 "); menu.setIcon(new ImageIcon(MainFrame.class.getResource("/images/base.png"))); menuBar.add(menu); JMenu mnNewMenu = new JMenu("\u56FE\u4E66\u7C7B\u522B\u7BA1\u7406 "); mnNewMenu.setIcon(new ImageIcon(MainFrame.class.getResource("/images/bookTypeManager.png"))); menu.add(mnNewMenu); //图书类别添加 JMenuItem menuItem = new JMenuItem("\u56FE\u4E66\u7C7B\u522B\u6DFB\u52A0"); menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BookTypeAddInterFrame bookTypeAddInterFrame=new BookTypeAddInterFrame(); bookTypeAddInterFrame.setVisible(true); table.add(bookTypeAddInterFrame); } }); menuItem.setIcon(new ImageIcon(MainFrame.class.getResource("/images/add.png"))); mnNewMenu.add(menuItem); //图书类别维护 JMenuItem menuItem_1 = new JMenuItem("\u56FE\u4E66\u7C7B\u522B\u7EF4\u62A4"); menuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BookTypeManageInterFrame bookTypeManageInterFrame=new BookTypeManageInterFrame(); bookTypeManageInterFrame.setVisible(true); table.add(bookTypeManageInterFrame); } }); menuItem_1.setIcon(new ImageIcon(MainFrame.class.getResource("/images/edit.png"))); mnNewMenu.add(menuItem_1); JMenu menu_1 = new JMenu("\u56FE\u4E66\u7BA1\u7406"); menu_1.setIcon(new ImageIcon(MainFrame.class.getResource("/images/bookManager.png"))); menu.add(menu_1); //图书添加 JMenuItem menuItem_2 = new JMenuItem("\u56FE\u4E66\u6DFB\u52A0"); menuItem_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BookAddInterFrame bookAddInterFrame=new BookAddInterFrame(); bookAddInterFrame.setVisible(true); table.add(bookAddInterFrame); } }); menuItem_2.setIcon(new ImageIcon(MainFrame.class.getResource("/images/add.png"))); menu_1.add(menuItem_2); //图书维护 JMenuItem menuItem_3 = new JMenuItem("\u56FE\u4E66\u7EF4\u62A4"); menuItem_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BookManageInterFrame bookManageInterFrame=new BookManageInterFrame(); bookManageInterFrame.setVisible(true); table.add(bookManageInterFrame); } }); menuItem_3.setIcon(new ImageIcon(MainFrame.class.getResource("/images/edit.png"))); menu_1.add(menuItem_3); //安全退出 JMenuItem menuItem_4 = new JMenuItem("\u5B89\u5168\u9000\u51FA"); menuItem_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//弹出退出确认提示框 int res=JOptionPane.showConfirmDialog(null, "确定要退出吗?"); //确定退出 if(res==JOptionPane.OK_OPTION){
dispose(); } //否则继续留在该界面 } }); menuItem_4.setIcon(new ImageIcon(MainFrame.class.getResource("/images/exit.png"))); menu.add(menuItem_4); JMenu menu_2 = new JMenu("\u5173\u4E8E\u6211\u4EEC"); menu_2.setIcon(new ImageIcon(MainFrame.class.getResource("/images/about.png"))); menuBar.add(menu_2); //关于我们 JMenuItem menuItem_5 = new JMenuItem("\u5173\u4E8E\u6211\u4EEC"); menuItem_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//新建一个图书内部窗体 LibraryInterFrame libraryInnerFrame=new LibraryInterFrame(); //显示图书内部窗体 libraryInnerFrame.setVisible(true); //将图书内部窗体显示到主界面桌面窗格中 table.add(libraryInnerFrame); } }); menuItem_5.setIcon(new ImageIcon(MainFrame.class.getResource("/images/about.png"))); menu_2.add(menuItem_5); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); //定义主界面桌面窗格界面,用于装载内部窗体 table = new JDesktopPane(); table.setBackground(Color.LIGHT_GRAY); contentPane.add(table, BorderLayout.CENTER); //设置窗口最大化 setExtendedState(JFrame.MAXIMIZED_BOTH); } }
package cn.ac.azure.view; import java.awt.EventQueue; import java.awt.Font; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.table.DefaultTableModel; import cn.ac.azure.dao.BookTypeDao; import cn.ac.azure.model.BookType; import cn.ac.azure.util.DBTool; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JPanel; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.JTextArea; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class BookTypeManageInterFrame extends JInternalFrame {
private JTextField s_bookTypeNameText; private JTable bookTypeTable; private BookTypeDao bookTypeDao=new BookTypeDao(); private JTextField idText; private JTextField bookTypeNameText; private JTextArea bookTypeDescText; /** * Launch the application. */ public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BookTypeManageInterFrame frame = new BookTypeManageInterFrame(); frame.setVisible(true); } catch (Exception e) {
e.printStackTrace(); } } }); } /** * Create the frame. */ public BookTypeManageInterFrame() {
//改变系统默认字体 Font font = new Font("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 instanceof javax.swing.plaf.FontUIResource) {
UIManager.put(key, font); } } setIconifiable(true); setClosable(true); setTitle("图书类别管理"); setBounds(400, 100, 535, 489); JScrollPane scrollPane = new JScrollPane(); JLabel label = new JLabel("图书类别名称:"); s_bookTypeNameText = new JTextField(); s_bookTypeNameText.setColumns(10); //查询按钮 JButton searchBtn = new JButton("查询"); searchBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchActionPerformed(e); } }); searchBtn.setIcon(new ImageIcon(BookTypeManageInterFrame.class.getResource("/images/search.png"))); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(null, "\u8868\u5355\u64CD\u4F5C", TitledBorder.LEADING, TitledBorder.TOP, null, null)); GroupLayout groupLayout = new GroupLayout(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 = new JLabel("编号:"); idText = new JTextField(); idText.setEditable(false); idText.setColumns(10); JLabel label_2 = new JLabel("图书类别名称:"); bookTypeNameText = new JTextField(); bookTypeNameText.setColumns(10); JLabel label_3 = new JLabel("描述:"); bookTypeDescText = new JTextArea(); //修改按钮 JButton modifyBtn = new JButton("修改"); modifyBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bookTypeUpdateActionPerformed(e); } }); modifyBtn.setIcon(new ImageIcon(BookTypeManageInterFrame.class.getResource("/images/modify.png"))); //删除按钮 JButton deleteBtn = new JButton("删除"); deleteBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bookTypeDeleteActionPerformed(e); } }); deleteBtn.setIcon(new ImageIcon(BookTypeManageInterFrame.class.getResource("/images/delete.png"))); GroupLayout gl_panel = new GroupLayout(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 = new JTable(); //表格鼠标点击事件 bookTypeTable.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
bookTypeTableMousePressed(e); } }); bookTypeTable.setModel(new DefaultTableModel( new Object[][] {
}, new String[] {
"编号", "图书类别名称", "图书类别描述" } ) {
boolean[] columnEditables = new boolean[] {
false, false, false }; public boolean isCellEditable(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(new LineBorder(new java.awt.Color(127,157,185), 1, false)); //构造函数中调用填充表格数据函数,全部图书类别显示在表格中 fillTable(new BookType()); } /** * 图书类别删除事件处理 * @param evt */ private void bookTypeDeleteActionPerformed(ActionEvent evt) {
//获得表单中编号的值id String 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(new BookType()); }else{
//删除失败,弹出提示框 JOptionPane.showMessageDialog(null, "修改数据失败(u_u)"); } } catch (SQLException e) {
//记录日志 e.printStackTrace(); throw new RuntimeException("删除记录失败!",e); }finally{
//关闭数据库 DBTool.close(con); } } /** * 图书类别修改事件处理 * @param evt */ private void bookTypeUpdateActionPerformed(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=new BookType(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(new BookType()); }else{
//修改失败,弹出提示框 JOptionPane.showMessageDialog(null, "修改数据失败(u_u)"); } } catch (SQLException e) {
//记录日志 e.printStackTrace(); throw new RuntimeException("修改图书类别失败",e); }finally{
//关闭数据路连接 DBTool.close(con); } } /** * 表格鼠标点击事件处理 * @param e */ private void bookTypeTableMousePressed(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 */ private void searchActionPerformed(ActionEvent evt) {
//获取图书类别输入框里的内容 String s_bookTypeName=s_bookTypeNameText.getText(); //新建一个图书类别并初始化 BookType bookType=new BookType(); //将输入框的内容设置成新建图书类别的图书类别名称 bookType.setBookTypeName(s_bookTypeName); //根据图书类别查询图书类别 fillTable(bookType); } /** * 在表格中填充数据 * @param bookType 传入bookType对象 */ private void fillTable(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=new Vector(); 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(); throw new RuntimeException("查询失败"); }finally{
//关闭数据库 DBTool.close(con); } } /** * 清空表单数据 */ private void resetValue(){
idText.setText(""); bookTypeNameText.setText(""); bookTypeDescText.setText(""); s_bookTypeNameText.setText(""); } }
package cn.ac.azure.view; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.SQLException; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.border.LineBorder; import cn.ac.azure.dao.BookTypeDao; import cn.ac.azure.model.BookType; import cn.ac.azure.util.DBTool; /** * 图书类别内部添加窗体 * @author green * */ public class BookTypeAddInterFrame extends JInternalFrame {
//图书类别名称输入框 private JTextField bookTypeNameText; //图书类别描述输入框 private JTextArea bookTypeDescText; //重置按钮 private JButton resetBtn; //添加按钮 private JButton addBtn; //图书类别数据库访问对象 private BookTypeDao bookTypeDao; /** * Launch the application. */ public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BookTypeAddInterFrame frame = new BookTypeAddInterFrame(); frame.setVisible(true); } catch (Exception e) {
e.printStackTrace(); } } }); } /** * Create the frame. */ public BookTypeAddInterFrame() {
//改变系统默认字体 Font font = new Font("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 instanceof javax.swing.plaf.FontUIResource) {
UIManager.put(key, font); } } setClosable(true); setIconifiable(true); setTitle("图书类别添加"); setBounds(100, 100, 487, 342); JLabel label = new JLabel("图书类别名称:"); bookTypeNameText = new JTextField(); bookTypeNameText.setColumns(10); JLabel label_1 = new JLabel("图书类别描述:"); bookTypeDescText = new JTextArea(); //添加按钮 addBtn = new JButton("添加"); addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addActionPerformed(e); } }); //重置按钮 resetBtn = new JButton("重置"); resetBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resetActionPerformed(e); } }); GroupLayout groupLayout = new GroupLayout(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(new LineBorder(new java.awt.Color(127,157,185), 1, false)); } /** * 添加事件处理 * @param evt */ private void addActionPerformed(ActionEvent evt) {
//获取输入框的值 String bookTypeName=bookTypeNameText.getText(); String bookTypeDesc=bookTypeDescText.getText(); if(bookTypeName==null || "".equals(bookTypeName.trim())){
JOptionPane.showMessageDialog(null,"图书类别不能为空!"); return; } //新建图书类别实体对象 BookType bookType=new BookType(bookTypeName, bookTypeDesc); //定义数据库连接 Connection con=null; try {
//获取数据库连接 con=DBTool.getConnetion(); //初始化图书类别对象BookTypeDao bookTypeDao=new BookTypeDao(); //调用图书类别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(); throw new RuntimeException("添加图书失败",e); }finally{
//关闭数据库 DBTool.close(con); } } /** * 重置事件处理 * @param evt */ private void resetActionPerformed(ActionEvent evt) {
//置空图书类别名称输入框 bookTypeNameText.setText(""); //置空图书类别描述输入框 bookTypeDescText.setText(""); } }
package cn.ac.azure.view; import java.awt.EventQueue; import java.awt.Font; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.table.DefaultTableModel; import cn.ac.azure.dao.BookDao; import cn.ac.azure.dao.BookTypeDao; import cn.ac.azure.model.Book; import cn.ac.azure.model.BookType; import cn.ac.azure.util.DBTool; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class BookManageInterFrame extends JInternalFrame {
private JTextField s_bookNameText; private JTextField s_authorText; private JTable bookTable; private JComboBox s_bookTypecomboBox; private BookTypeDao bookTypeDao; private BookDao bookDao; private JTextField idText; private JTextField bookNameText; private JTextField priceText; private JTextField authorText; private JTextField bookDescText; private final ButtonGroup buttonGroup = new ButtonGroup(); private JComboBox bookTypeComboBox; private JRadioButton maleBtn; private JRadioButton femaleBtn; /** * Launch the application. */ public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BookManageInterFrame frame = new BookManageInterFrame(); frame.setVisible(true); } catch (Exception e) {
e.printStackTrace(); } } }); } /** * Create the frame. */ public BookManageInterFrame() {
//改变系统默认字体 Font font = new Font("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 instanceof javax.swing.plaf.FontUIResource) {
UIManager.put(key, font); } } setIconifiable(true); setClosable(true); setTitle("图书管理 "); setBounds(100, 100, 767, 528); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(null, "搜索条件", TitledBorder.LEADING, TitledBorder.TOP, null, null)); JScrollPane scrollPane = new JScrollPane(); JPanel panel_1 = new JPanel(); panel_1.setBorder(new TitledBorder(null, "表单操作", TitledBorder.LEADING, TitledBorder.TOP, null, null)); GroupLayout groupLayout = new GroupLayout(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 = new JLabel("编号:"); idText = new JTextField(); idText.setColumns(10); JLabel label_3 = new JLabel("图书名称:"); bookNameText = new JTextField(); bookNameText.setColumns(10); JLabel label_4 = new JLabel("作者性别:"); maleBtn = new JRadioButton("男"); buttonGroup.add(maleBtn); femaleBtn = new JRadioButton("女"); buttonGroup.add(femaleBtn); JLabel label_5 = new JLabel("价格:"); priceText = new JTextField(); priceText.setColumns(10); JLabel label_6 = new JLabel("图书作者:"); authorText = new JTextField(); authorText.setColumns(10); JLabel label_7 = new JLabel("图书类别:"); bookTypeComboBox = new JComboBox(); JLabel label_8 = new JLabel("图书描述:"); bookDescText = new JTextField(); bookDescText.setColumns(10); //修改按钮 JButton modifyBtn = new JButton("修改"); modifyBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modifyBookActionPerformed(e); } }); modifyBtn.setIcon(new ImageIcon(BookManageInterFrame.class.getResource("/images/modify.png"))); //删除按钮 JButton deleteBtn = new JButton("删除"); deleteBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteBookActionPerformed(e); } }); deleteBtn.setIcon(new ImageIcon(BookManageInterFrame.class.getResource("/images/delete.png"))); GroupLayout gl_panel_1 = new GroupLayout(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 = new JTable(); //表格鼠标按下事件 bookTable.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
tableMousePressed(e); } }); bookTable.setModel(new DefaultTableModel( new Object[][] {
}, new String[] {
"编号", "图书名称", "图书作者", "图书性别", "图书价格", "图书类别", "图书描述" } ) {
boolean[] columnEditables = new boolean[] {
false, false, false, false, false, false, false }; public boolean isCellEditable(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 = new JLabel("图书名称:"); s_bookNameText = new JTextField(); s_bookNameText.setColumns(10); JLabel label = new JLabel("图书作者:"); s_authorText = new JTextField(); s_authorText.setColumns(10); JLabel label_1 = new JLabel("图书类别:"); s_bookTypecomboBox = new JComboBox(); //图书查询按钮 JButton s_searchBtn = new JButton("查询"); s_searchBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchActionPerformed(e); } }); s_searchBtn.setIcon(new ImageIcon(BookManageInterFrame.class.getResource("/images/search.png"))); GroupLayout gl_panel = new GroupLayout(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(new Book()); } /** * 图书修改事件 * @param evt */ private void modifyBookActionPerformed(ActionEvent evt) {
//获取图书id String id=idText.getText(); //获取图书名称 String bookName=bookNameText.getText(); //获取图书作者 String author=authorText.getText(); //或者作者性别 String sex="男"; if(femaleBtn.isSelected()){
sex="女"; } //获取图书价格 String price=priceText.getText(); //获取图书id BookType 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=new Book(Integer.parseInt(id),bookName, author, sex, Float.parseFloat(price), bookTypeId, bookDesc, null); System.out.println("从获取的图书信息创建图书对象:"+book); //定义数据库连接 Connection con=null; try {
//获取数据库连接 con=DBTool.getConnetion(); //初始化图书数据访问对象 bookDao=new BookDao(); //执行图书访问对象的修改方法,并获得修改的记录数 int res=bookDao.update(con, book); if(res==1){
//为1 JOptionPane.showMessageDialog(null,"图书修改成功n_n"); //刷新图书表格显示 fillBookTable(new Book()); //重置操作栏 resetValue(); }else{
//为0 JOptionPane.showMessageDialog(null,"图书修改失败u_u"); } } catch (SQLException e) {
//记录日志 e.printStackTrace(); throw new RuntimeException("修改图书失败",e); }finally{
//关闭数据库连接 DBTool.close(con); } } /** * 图书删除事件 * @param evt */ private void deleteBookActionPerformed(ActionEvent evt) {
//获取图书id String id=idText.getText(); //判断是否id是否为空 if(id==null || "".equals(id)){
//为空 JOptionPane.showMessageDialog(null, "请选中要删除的行!"); //给用户提示 return; } //定义数据库连接对象 Connection con=null; try {
//初始化数据库连接对象 con=DBTool.getConnetion(); //初始化图书数据访问对象 bookDao=new BookDao(); //执行图书访问对象的删除方法并返回删除的记录数 int res=bookDao.delete(con, Integer.parseInt(id)); if(res==1){
//为1 JOptionPane.showMessageDialog(null, "图书删除成功n_n"); //刷新图书表格显示 fillBookTable(new Book()); //重置操作栏 resetValue(); }else{
//为其他 JOptionPane.showMessageDialog(null, "图书删除失败u_u"); } } catch (SQLException e) {
//记录日志 e.printStackTrace(); throw new RuntimeException("删除图书失败",e); }finally{
//记得关闭数据库(******) DBTool.close(con); } } /** * 重置操作栏的所有值 */ private void resetValue(){
idText.setText(""); bookNameText.setText(""); authorText.setText(""); maleBtn.setSelected(true); priceText.setText(""); fillBookTypeComboBox("modify"); bookDescText.setText(""); } /** * 表格鼠标按下事件处理 * @param evt */ private void tableMousePressed(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 事件对象 */ private void searchActionPerformed(ActionEvent evt) {
//获取查询的条件 String bookName=s_bookNameText.getText(); //图书名称 String author=s_authorText.getText(); //图书作者 String bookTypeName=s_bookTypecomboBox.getSelectedItem().toString(); //图书类别 //对图书类别"请选择..."换成"" if("请选择...".equals(bookTypeName)){
bookTypeName=""; } //生成带有条件的图书对象 Book book=new Book(); book.setBookName(bookName); //设置图书名称条件 book.setAuthor(author); //设置图书作者条件 book.setBookTypeName(bookTypeName); //设置图书类别条件 //调用table填充函数,根据查询结果重新填充表格 fillBookTable(book); } /** * 初始化图书类别下拉框 * @param type 根据不同的参数填充不同的下拉框 */ private void fillBookTypeComboBox(String type){
//定义一个图书类别,用于存储查询的图书类别 BookType s_bookType=null; //定义一个数据库连接 Connection con=null; try {
//获取数据库连接 con=DBTool.getConnetion(); //初始化图书类别访问数据对象 bookTypeDao=new BookTypeDao(); //查询图书类别,得到结果集 ResultSet rs=bookTypeDao.search(con, new BookType()); if("search".equals(type)){
BookType bookType=new BookType(); bookType.setBookTypeName("请选择..."); bookType.setId(-1); s_bookTypecomboBox.addItem(bookType); } //遍历结果集 while(rs.next()){
//如果有数据的话 //初始化接受查询的图书类别 s_bookType=new BookType(); //根据查询结果设置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(); throw new RuntimeException("初始化下拉框失败",e); }finally{
//关闭数据库连接 DBTool.close(con); } } /** * 初始化表格,列出所有的书籍 * @param book */ private void fillBookTable(Book book){
//获取表格的模型 DefaultTableModel dtm=(DefaultTableModel) bookTable.getModel(); //填充表格时设置成0行(相当于归零处理) dtm.setRowCount(0); //定义数据库连接 Connection con=null; try {
//获取数据库连接 con=DBTool.getConnetion(); //初始化图书数据访问对象 bookDao=new BookDao(); //按条件查询图书(这里没有条件,查出所有书籍) ResultSet rs=bookDao.search(con, book); //遍历查询结果 while(rs.next()){
//定义一个集合,由于存储图书信息 Vector v=new Vector(); 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(); throw new RuntimeException("初始化表格失败",e); }finally{
//关闭数据库连接 DBTool.close(con); } } }
package cn.ac.azure.view; import java.awt.EventQueue; import java.awt.Font; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.ButtonGroup; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.border.LineBorder; import cn.ac.azure.dao.BookDao; import cn.ac.azure.dao.BookTypeDao; import cn.ac.azure.model.Book; import cn.ac.azure.model.BookType; import cn.ac.azure.util.DBTool; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class BookAddInterFrame extends JInternalFrame {
private JTextField bookNameText; private JTextField authorText; private final ButtonGroup buttonGroup = new ButtonGroup(); private JTextField priceText; private JComboBox bookTypeComboBox; private JRadioButton maleBtn; private JRadioButton femaleBtn; private JTextArea bookDescText; private BookTypeDao bookTypeDao; private BookDao bookDao; /** * Launch the application. */ public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BookAddInterFrame frame = new BookAddInterFrame(); frame.setVisible(true); } catch (Exception e) {
e.printStackTrace(); } } }); } /** * Create the frame. */ public BookAddInterFrame() {
setIconifiable(true); setClosable(true); // 改变系统默认字体 Font font = new Font("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 instanceof javax.swing.plaf.FontUIResource) {
UIManager.put(key, font); } } setTitle("图书添加 "); setBounds(100, 100, 699, 449); JLabel label = new JLabel("图书名称:"); bookNameText = new JTextField(); bookNameText.setColumns(10); JLabel label_1 = new JLabel("图书作者:"); authorText = new JTextField(); authorText.setColumns(10); JLabel label_2 = new JLabel("作者性别:"); maleBtn = new JRadioButton("男"); buttonGroup.add(maleBtn); femaleBtn = new JRadioButton("女"); buttonGroup.add(femaleBtn); JLabel label_3 = new JLabel("图书价格:"); priceText = new JTextField(); priceText.setColumns(10); JLabel label_4 = new JLabel("图书类别:"); // 图书类别下拉框 bookTypeComboBox = new JComboBox(); JLabel label_5 = new JLabel("图书描述:"); bookDescText = new JTextArea(); // 图书添加按钮 JButton addBtn = new JButton("添加"); addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 图书添加按钮事件处理 bookAddActionPerformed(e); } }); addBtn.setIcon(new ImageIcon(BookAddInterFrame.class.getResource("/images/add.png"))); // 图书重置按钮 JButton resetBtn = new JButton("重置"); resetBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bookResetActionPerformed(e); } }); resetBtn.setIcon(new ImageIcon(BookAddInterFrame.class.getResource("/images/reset.png"))); GroupLayout groupLayout = new GroupLayout(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(new LineBorder(new java.awt.Color(127, 157, 185), 1, false)); // 在构造函数中调用图书类别下拉框初始化方法 fillBookTypeName(); // 在构造函数中初始化性别。默认为男 maleBtn.setSelected(true); } /** * 重置按钮事件处理 * * @param evt * 重置按钮事件对象 */ private void bookResetActionPerformed(ActionEvent evt) {
reset(); } /** * 图书添加界面信息重置 */ private void reset() {
bookNameText.setText(""); authorText.setText(""); maleBtn.setSelected(true); priceText.setText(""); bookTypeComboBox.setSelectedIndex(0); bookDescText.setText(""); } /** * 图书添加按钮事件处理 * * @param evt * 添加事件对象 */ private void bookAddActionPerformed(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(); // 获取图书类别id System.out.println("ID="+bookTypeId); String bookDesc = bookDescText.getText(); // 获取图书描述 // 根据获取的添加图书界面获取的信息创建图书对象 Book book = new Book(null, bookName, author, sex, price, bookTypeId, bookName, bookDesc); System.out.println("实体类:"+book); // 定义数据库连接 Connection con = null; try {
// 获取数据库连接 con = DBTool.getConnetion(); // 初始化图书数据访问对象 bookDao = new BookDao(); // 调用添加方法,向数据库添加书籍 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(); throw new RuntimeException("添加图书失败", e); } finally {
// 关闭数据库连接 DBTool.close(con); } } // 填充图书类别名称 private void fillBookTypeName() {
// 定义数据库连接对象 Connection con = null; // 定义图书类别,用于查询和储存查询的书籍 BookType bookType = null; try {
// 获取数据库连接 con = DBTool.getConnetion(); // 初始化图书类别访问对象 bookTypeDao = new BookTypeDao(); // 查询t_bookType中含有的图书类别 ResultSet rs = bookTypeDao.search(con, bookType); // 遍历查询结果 while (rs.next()) {
// 出事化图书类别 bookType = new BookType(); // 设置图书的id bookType.setId(rs.getInt("id")); // 设置图书的名称 bookType.setBookTypeName(rs.getString("bookTypeName")); // 将图书类别对象添加到下拉框中(这里添加对象,便于获得id) bookTypeComboBox.addItem(bookType.getBookTypeName()); } } catch (SQLException e) {
// 记录日志 e.printStackTrace(); throw new RuntimeException("初始化列表失败", e); } finally {
// 关闭数据路连接 DBTool.close(con); } } }
package cn.ac.azure.view; import java.awt.EventQueue; import javax.swing.JInternalFrame; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.ImageIcon; import java.awt.Font; import java.awt.Color; public class LibraryInterFrame extends JInternalFrame {
private static final long serialVersionUID = 1L; /** * Launch the application. */ public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LibraryInterFrame frame = new LibraryInterFrame(); frame.setVisible(true); } catch (Exception e) {
e.printStackTrace(); } } }); } /** * Create the frame. */ public LibraryInterFrame() {
//改变系统默认字体 Font font = new Font("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 instanceof javax.swing.plaf.FontUIResource) {
UIManager.put(key, font); } } setClosable(true); setIconifiable(true); setBounds(450, 150, 503, 300); JLabel label = new JLabel(""); label.setIcon(new ImageIcon(LibraryInterFrame.class.getResource("/images/library.png"))); JLabel label_1 = new JLabel("欢迎使用图书管理系统"); label_1.setForeground(Color.GREEN); label_1.setBackground(Color.GREEN); label_1.setFont(new Font("宋体", Font.PLAIN, 20)); GroupLayout groupLayout = new GroupLayout(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); } }
/* 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 -- ---------------------------- DROP TABLE IF EXISTS `t_book`; CREATE TABLE `t_book` ( `id` int(50) NOT NULL AUTO_INCREMENT, `bookName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `author` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `sex` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `price` double(50, 2) NULL DEFAULT NULL, `bookTypeId` int(50) NULL DEFAULT NULL, `bookTypeName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `bookDesc` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `fk_booktype`(`bookTypeId`) USING BTREE, CONSTRAINT `fk_booktype` FOREIGN KEY (`bookTypeId`) REFERENCES `t_booktype` (`id`) ON DELETE SET NULL ON UPDATE SET NULL ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of t_book -- ---------------------------- INSERT INTO `t_book` VALUES (1, '《人间失格》', '(日)太宰治', '男', 66.00, 1, '小说', '(日本小说家太宰治代表作,一个对村上春树影响至深的绝望凄美故事)'); INSERT INTO `t_book` VALUES (2, '《三体》', '刘慈欣', '女', 55.80, 1, '小说', '刘慈欣代表作,亚洲首部“雨果奖”获奖作品!\r\n《三体》第73届世界科幻雨果奖获奖作品,银河奖特别奖,《三体3》轨迹奖长篇科幻小说!2017年世界雨果奖提名作品。'); INSERT INTO `t_book` VALUES (3, '《人生海海》', '麦家', '男', 55.00, 2, '文化科学', '麦家重磅力作,莫言、董卿盛赞,连续两年高居各大畅销榜,发行量超180万册,罗一舟同款书)\r\n上校赢了所有的仗,却败给一个不足道的秘密。茅盾文学奖得主麦家暌违8年,打磨5年,挑战常人不敢落笔之处,解密人性的荒唐与高尚。人生海海,何必在意一时沉浮!'); INSERT INTO `t_book` VALUES (4, '《大国崛起》', '唐晋', '男', 50.40, 2, '历史', '以历史的眼光和全球的视野解读15世纪以来9个世界性大国崛起的历史,中国能否成为第十个崛起的大国?'); INSERT INTO `t_book` VALUES (5, '《中华人民共和国民法典》', '法律出版社', '男', 8.10, 2, '哲学、社会', '民法典是新中国首部以“法典”命名的法律,是新时代我国社会主义法治建设的重大成果,是为百姓生活量身定制的权利宝典。自2021年1月1日起施行。'); -- ---------------------------- -- Table structure for t_booktype -- ---------------------------- DROP TABLE IF EXISTS `t_booktype`; CREATE TABLE `t_booktype` ( `id` int(50) NOT NULL AUTO_INCREMENT, `bookTypeName` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `bookTypeDesc` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 25 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of t_booktype -- ---------------------------- INSERT INTO `t_booktype` VALUES (1, 'A 马克思主义、列宁主义、毛泽东思想、邓小平理论', 'A 马克思主义、列宁主义、毛泽东思想、邓小平理论'); INSERT INTO `t_booktype` VALUES (2, 'B 哲学、宗教', 'B 哲学、宗教'); INSERT INTO `t_booktype` VALUES (3, 'C 社会科学总论', 'C 社会科学总论'); INSERT INTO `t_booktype` VALUES (4, 'D 政治、法律', 'D 政治、法律'); INSERT INTO `t_booktype` VALUES (5, 'F 经济', 'F 经济'); INSERT INTO `t_booktype` VALUES (6, 'G 文化、科学、教育、体育', 'G 文化、科学、教育、体育'); INSERT INTO `t_booktype` VALUES (7, 'H 语言、文字', 'H 语言、文字'); INSERT INTO `t_booktype` VALUES (8, 'I 文学', 'I 文学'); INSERT INTO `t_booktype` VALUES (9, 'J 艺术', 'J 艺术'); INSERT INTO `t_booktype` VALUES (10, 'K 历史、地理', 'K 历史、地理'); INSERT INTO `t_booktype` VALUES (11, 'N 自然科学总论', 'N 自然科学总论'); INSERT INTO `t_booktype` VALUES (12, 'O 数理科学和化学', 'O 数理科学和化学'); INSERT INTO `t_booktype` VALUES (13, 'Q 生物科学', 'Q 生物科学'); INSERT INTO `t_booktype` VALUES (14, 'R 医药、卫生 ', 'R 医药、卫生'); INSERT INTO `t_booktype` VALUES (15, 'S 农业科学', 'S 农业科学'); INSERT INTO `t_booktype` VALUES (16, 'T-TN 工业技术', 'T-TN 工业技术'); INSERT INTO `t_booktype` VALUES (17, 'TP 自动化技术、计算机技术', 'TP 自动化技术、计算机技术'); INSERT INTO `t_booktype` VALUES (18, 'TQ 化学工业', 'TQ 化学工业'); INSERT INTO `t_booktype` VALUES (19, 'TU 建筑科学', 'TU 建筑科学'); INSERT INTO `t_booktype` VALUES (20, 'TV 水利工程', 'TV 水利工程'); INSERT INTO `t_booktype` VALUES (21, 'U 交通运输', 'U 交通运输'); INSERT INTO `t_booktype` VALUES (22, 'V 航空、航天', 'V 航空、航天'); INSERT INTO `t_booktype` VALUES (23, 'X 环境科学、安全科学', 'X 环境科学、安全科学'); INSERT INTO `t_booktype` VALUES (24, 'Z 综合性图书', 'Z 综合性图书'); -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` int(50) NOT NULL AUTO_INCREMENT, `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of t_user -- ---------------------------- INSERT INTO `t_user` VALUES (1, '11', ''); SET FOREIGN_KEY_CHECKS = 1;
https://download.csdn.net/download/weixin_/
今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。