Swing入门级项目全程实录第3讲
惯例广告一发,对于初学真,真的很有用www.java1234.com,去试试吧!
1、增加数据表t_booktype
1.1创建数据表t_booktype
1.2创建数据表项id int pk auto、bookTypeName varchar 20、bookTypeDesc varchar 20
2、创建BookTypeModel
2.1创建BookType类
2.2构造set、get方法
/** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the bookTypeName */ public String getBookTypeName() { return bookTypeName; } /** * @param bookTypeName the bookTypeName to set */ public void setBookTypeName(String bookTypeName) { this.bookTypeName = bookTypeName; } /** * @return the bookTypeDesc */ public String getBookTypeDesc() { return bookTypeDesc; } /** * @param bookTypeDesc the bookTypeDesc to set */ public void setBookTypeDesc(String bookTypeDesc) { this.bookTypeDesc = bookTypeDesc; }
3、创建Panel控件
3.1在MainFrm中创建Panel控件,名称改为jp_table;
4、创建BookTypeAddInterFrm
4.1创建BookTypeAddInterFrm,title图书类别添加
4.2添加2个jLable、1个jTextField、1个jTextAreaField、2个jButton控件
4.3修改控件属性并美化
5、在MainFrm添加BookTypeAddInterFrm
BookTypeAddInterFrm bookTypeAddInterFrm=new BookTypeAddInterFrm(); bookTypeAddInterFrm.setVisible(true); jp_table.add(bookTypeAddInterFrm);
6、BookTypeAddInterFrm添加、重置实现
6.1重置实现
private void resetValue() { jt_booktypename.setText(""); jt_booktypedesc.setText(""); }
6.2.1创建BookTypeDao,添加bookTypeAdd方法
public int bookTypeAdd(Connection con,BookType bookType) throws Exception{ String sql="insert into t_booktype values(null,?,?)"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, bookType.getBookTypeName()); pstmt.setString(2, bookType.getBookTypeDesc()); return pstmt.executeUpdate(); }
String bookTypeName=jt_booktypename.getText(); String bookTypeDescString=jt_booktypedesc.getText(); if(StringUtil.isEmpty(bookTypeName)){ JOptionPane.showMessageDialog(null, "图书类别名称不能为空"); return; } BookType bookType=new BookType(bookTypeName,bookTypeDescString);
public BookType() { super(); // TODO Auto-generated constructor stub } public BookType(String bookTypeName, String bookTypeDesc) { super(); this.bookTypeName = bookTypeName; this.bookTypeDesc = bookTypeDesc; }
6.2.3建立数据库连接,实现添加数据
DbUtil dbUtil=new DbUtil(); BookTypeDao bookTypeDao=new BookTypeDao();
Connection con=null; try { con=dbUtil.getCon(); int n=bookTypeDao.bookTypeAdd(con, bookType); if(n==1){ JOptionPane.showMessageDialog(null, "图书类别添加成功"); resetValue(); }else{ JOptionPane.showMessageDialog(null, "图书类别添加失败"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); JOptionPane.showMessageDialog(null, "图书类别添加失败"); }finally{ try { dbUtil.closeCon(con); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }