O gerenciamento de informações do livro é semelhante ao gerenciamento de informações do leitor. Inclui duas partes: adição de livros e consulta e modificação de livros. A adição de informações do livro requer a entrada correta de oito informações do livro, e o número do ISBN é único. Durante o processo de implementação, o ISBN deve ser usado como chave primária. Vamos ver o processo de implementação:
Livros no banco de dados:
O processo de adicionar livros:
Conteúdo do banco de dados adicionado:
Consulta e modificação dos livros: O processo de consulta pode ser consultado de acordo com diferentes condições, como ISBN, autor, editor, nome do livro etc., e todos os livros são exibidos na lista por padrão. Depois de inserir as condições da consulta, os resultados da consulta são exibidos na tabela.
Este módulo usa o painel de tags, que pode consultar facilmente as informações necessárias. Quando o processo de modificação entra no número do ISBN e pressione Enter para exibir todas as informações do livro abaixo, todo o conteúdo será atualizado após a modificação das informações do livro.
Consulta de livros:
Modificar informações do livro:
Adicione o código -fonte do livro da seguinte forma: AddBook.java
pacote pdsu.bbm.View; importar java.awt.borderlayout; importar java.awt.flowlayout; importar java.awt.font; importar java.awt.image; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar java.text.parseException; importar java.text.simpledateFormat; importar java.util.date; importar java.util.iterator; importar java.util.list; importar javax.swing.buttongroup; importar javax.swing.imageicon; importar javax.swing.jbutton; importar javax.swing.jcombobox; importar javax.swing.jframe; importar javax.swing.jlabel; importar javax.swing.JOptionPane; importar javax.swing.jpanel; importar javax.swing.jtextfield; importar pdsu.bbm.dao.bookdao; importar pdsu.bbm.dao.booktypedao; importar pdsu.bbm.model.book; importar pdsu.bbm.model.booktype; classe pública AddBook estende JFRame implementa o ActionListener {private JPanel ContentPane; Private Jlabel Label_1; Private Jlabel lbll; Private Jlabel Label_2; Private Jlabel Label_3; Private Jlabel Label_4; Private Jlabel Label_5; JPanel Centerppanel; JButton Button1, Button2, Button3; Private JCOMBOBOX combobox_1; ICON da imagem = new Imageicon ("Image/icon.png"). GetImage (); Private JTextfield isbnfiled; Private JTextfield Publishfield; Private JTextfield Publishdatefield; Private JTextfield Publishtime; Private JTextfield UnitPriceField; Private JTextfield BookNamefield; Private JTextfield Authorfiled; public static void main (string [] args) {new addbook (); } public addbook () {Settitle ("Adicione informações do livro"); Setsize (555, 333); seticonimage (ícone); setLocationRelativeTo (NULL); Settitle ("Adicione informações do livro"); SetSize (555, 334); setLocationRelativeTo (NULL); setvisible (true); CenterppAnel = new JPanel (); CenterppAnel.setLayout (NULL); JLABEL LABEL1 = novo Jlabel ("ISBN:"); Label1.setFont (New Font ("宋体", font.plain, 20)); Label1.setbounds (71, 26, 95, 42); CenterppAnel.add (Label1); Isbnfiled = new jtextfield (); Isbnfiled.setbounds (120, 30, 110, 30); CenterppAnel.add (isbnfiled); Isbnfiled.setColumns (10); Rótulo jlabel = new jlabel ("categoria:"); LABEL.SETFont (New Font ("Zongyi", Font.Plain, 20)); Label.setbounds (306, 30, 116, 35); Centerpppanel.add (etiqueta); Label_1 = novo Jlabel ("Título do livro:"); LABEL_1.SETFONT (new Font ("宋体", font.plain, 20)); Label_1.setbounds (50, 75, 154, 50); CenterppAnel.add (Label_1); lbll = new jlabel ("autor:"); lbll.setFont (nova fonte ("宋体", font.plain, 20)); lbll.setbounds (306, 75, 137, 50); CenterppAnel.add (lbll); Label_2 = new Jlabel ("Publisher:"); LABEL_2.SETFONT (new Font ("宋体", font.plain, 20)); LABEL_2.SETBOUNDS (50, 130, 154, 50); CenterppAnel.add (Label_2); LABEL_3 = new Jlabel ("宋体:"); LABEL_3.SETFONT (new Font ("宋体", font.plain, 20)); Label_3.SetBounds (285, 135, 137, 50); CenterppAnel.add (Label_3); publishfield = new jtextfield (); publishfield.setColumns (10); publishfield.setbounds (120, 143, 110, 30); CenterppAnel.add (Publishfield); publishdatefield = new JTextfield (); publishdatefield.setColumns (10); publishdatefield.setbounds (380, 143, 120, 30); CenterppAnel.add (Publishdatefield); Label_4 = novo JLabel ("Número de impressão:"); LABEL_4.SETFont (new Font ("宋体", font.plain, 20)); Label_4.SetBounds (28, 190, 154, 50); CenterppAnel.add (Label_4); PublishTime = new JTextfield (); publishtime.setColumns (10); publishtime.setbounds (120, 203, 110, 30); CenterppAnel.add (Publishtime); Label_5 = novo Jlabel ("宋体:"); LABEL_5.SETFont (new Font ("宋体", font.plain, 20)); Label_5.setBounds (305, 194, 84, 42); CenterppAnel.add (Label_5); unitpricefield = new jtextfield (); unitpricefield.setColumns (10); UnitPriceField.setBounds (380, 203, 120, 30); CenterppAnel.add (UnitPriceField); getContentPane (). Add (CenterppAnel, borderlayout.center); bookNamefield = new JTextfield (); booknamefield.setColumns (10); booknamefield.setbounds (120, 86, 110, 30); CenterppAnel.add (booknamefield); AuthorFiled = new JTextfield (); AuthorFiled.setColumns (10); AuthorFiled.setBounds (380, 86, 120, 30); CenterppAnel.add (Authorfiled); Lista <Tooktype> rs = booktypedao.SelectBooktype (); Iterator <Booktype> iterator = rs.iterator (); String [] allTypeName = new String [rs.size ()]; int i = 0; while (iterator.hasnext ()) {string typename = iterator.Next (). getTypeName (); AllTypeName [i] = typename; i ++; } ComboBox_1 = novo JCOMBOBOX (AllTypeName); ComboBox_1.setbounds (380, 30, 120, 30); ComboBox_1.setFont (new Font ("安体", font.plain, 16)); CenterppAnel.add (ComboBox_1); ButtOngroup Group = new ButtongRoup (); Jpanel painel2 = new jpanel (); painel2.SetLayout (new FlowLayout ()); Button1 = novo JButton ("Add"); Button1.setFont (nova fonte ("宋体", font.plain, 20)); Button2 = novo jbutton ("宋体", font.plain, 20)); Button3 = novo JButton ("Redefinir"); button3.setFont (nova fonte ("宋体", font.plain, 20)); painel2.Add (Button1); painel2.Add (Button3); painel2.Add (Button2); botão1.AddactionListener (isto); Button2.AddactionListener (isto); Button3.AddactionListener (isto); getContentPane (). Add (Panel2, BorderLayout.South); setvisible (true); } @Suppresswarnings ("não utilizados") public void actionPerformed (ActionEvent e) {if (e.getSource () == button1) {string isbn = isbnfiled.getText (). Tostring (); String bookName = booknamefield.getText (); String Author = AuthorFiled.getText (); String selectType = ComboBox_1.getSelectedItem (). ToString (); String publish = publishfield.getText (); String publishdate = publishdatefield.getText (); String time = publishTime.getText (). TRIM (); Price da String = UnitPriceField.getText (). TRIM (); if (isbn.equals ("") || bookname.equals ("") || author.equals ("") || selectype.equals ("") || publish.equals ("") || publishdate.equals ("") || time.equ ("). retornar; } else {booktype bt = new booktype (); Livro do livro = novo livro (); book.setIsbn (ISBN); book.setbookName (bookName); book.setAuthor (autor); bt.setTypeName (selectType); int m = 0; Lista <Tooktype> List = Booktypedao .SelectIdByTyPename (SelectType); Iterator <Booktype> item = list.iterator (); while (it.hasnext ()) {m = item.Next (). getId (); } book.setTypeId (M + ""); book.setPublish (publish); tente {book.setPublishtime (Integer.parseint (tempo)); book.setUnitPrice (Integer.parseint (preço)); } catch (numberFormatexception e1) {e1.printStackTrace (); } SimpleDateFormat Sdf = new SimpleDateFormat ("AAAA-MM-DD"); Data regdate = null; tente {regdate = sdf.parse (publicHdate); } catch (parseexception e1) {joptionpane.showMessagedialog (this, "por favor, digite a data correta"); publishdatefield.settext (""); } book.setpublishdate (regdate); if (regdate == null) retornar; if (bookdao.SelectBookbyisbn (isbn)! = null) {joptionPane.showMessagedialog (isto, "este número do ISBN já existe"); retornar; } else if (bookdao.insertbook (livro)! = 0) {JoptionPane.ShowMessagedialog (this, "adicionado com sucesso"); } else JoptionPane.showMessagedialog (isto, "Adicionar falhou"); }} if (e.getSource () == button3) {isbnfiled.settext (""); booknamefield.settext (""); Autorfield.settext (""); publishfield.settext (""); publishdatefield.settext (""); publishtime.settext (""); unitpricefield.settext (""); unitpricefield.settext (""); } if (e.getSource () == Button2) {DispePe (); new mainwindow (); }}} Consulta de livros e modificar o código -fonte: bookselectendmodify.java
pacote pdsu.bbm.View; importar java.awt.borderlayout; importar java.awt.dimension; importar java.awt.font; importar java.awt.gridlayout; importar java.awt.image; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar java.text.simpledateFormat; importar java.util.arraylist; importar java.util.date; importar java.util.iterator; importar java.util.list; importar javax.swing.imageicon; importar javax.swing.jbutton; importar javax.swing.jcombobox; importar javax.swing.jframe; importar javax.swing.jlabel; importar javax.swing.JOptionPane; importar javax.swing.jpanel; importar javax.swing.jscrollpane; importar javax.swing.jtabbedpane; importar javax.swing.jtable; importar javax.swing.jtextfield; importar javax.swing.swingconstants; importar javax.swing.table.tablemodel; importar pdsu.bbm.dao.bookdao; importar pdsu.bbm.dao.booktypedao; importar pdsu.bbm.model.book; importar pdsu.bbm.model.booktype; Classe public BookSelectAndModify estende o JFRame implementa o ActionListener {// Defina o número de série privado estático final serialversionuid = 1L; Private Jtabbedpane Jtabbedpane; // Painel de tags // SelectJP Painel de consulta Select_ConditionJP Painel de lista suspensa Select_ResultJP Painel de botão Atualização de Atualização de JP // Painel de modificação Atualizejp, Botão do Botão do Botão do BOTONJP2 Private JPanel SelectJP, Select_conditionJP, Select_ResultJp, Buttonjp1, Livrojp, atualização, // Private JTextField SelectJtf, ISBNJTF, BookNamejtf, Authorjtf, PrintTimejtf, Publishjtf, PublishDatejtf, UnitPriceJtf; Private Jlabel Isbnjl, BookNamejl, AuthorJL, CategoryJL, PrintTimeJL, PublishJL, PublishDateJL, UnitPriceJL; // Foco! private jtable jTable; // Definir tabela privada jcombobox ChoiceJCB, booktypejcb; Private JScrollPane JScrollPane; Private JButton SelectJB, EXITJB, UPDATEJB, RESETJB; // Botão de consulta, botão de saída, botão de modificar, fechar o botão Tabrelodel Private GetSelect; Private String [] Title = {"ISBN", "Sequência de livros", "Nome do livro", "Autor", "Publisher", "Data da publicação", "Número de impressões", "Preço unitário"}; ICON da imagem = new Imageicon ("Image/icon.png"). GetImage (); public bookSelectAndModify () {super (); seticonimage (ícone); Settitle ("Consulta e modificação do livro"); setbounds (100, 100, 555, 400); setLocationRelativeTo (NULL); // jtabbedpane tabjtabbedPane = new jtabbedPane (); add (jtabbedpane); selectjp = new jpanel (); selectjp.setLayout (new BorderLayout ()); jtabbedpane.add ("Consulta de informações do livro", selectJP); // Painel de condição de consulta select_conditionJP = new JPanel (); ChoiceJCB = novo JCOMBOBOX (); String array [] = {"isbn", "Nome do livro", "Sequência de livros", "Autor", "Publisher", "All"}; // Defina como uma matriz unidimensional para (int i = 0; i <Array.length; } select_conditionjp.add (ChoiceJCB); selectjtf = new JTextfield (20); select_conditionjp.add (selectjtf); selectjp.add (select_conditionJP, borderlayout.north); // Painel de resultados de consulta select_ResultJP = new JPanel (); Bookdao dao = novo bookdao (); List <Book> list = Dao.SelectBook (); jtable = new jtable (getSelect (list), título); //! Defina o tamanho da tabela inalterado jtable.setAutoresizEMode (jtable.auto_resize_off); //! Defina a largura da coluna JTable.getColumnModel (). GetColumn (4) .SetPreferredWidth (175); jscrollPane = novo jscrollPane (jtable); // Adicione a tabela ao painel de rolagem // Mostrar a borda do painel de rolagem jscrollPane.setPreferredSize (nova dimensão (450, 170)); select_resultjp.add (jscrollPane); selectjp.add (select_resultjp, borderlayout.center); // Botão do botão de consulta botão botãojp1 = new jpanel (); selectjb = new jbutton ("Query"); selectjb.setFont (new Font ("Zongyi", font.plain, 20)); selectjb.addactionListener (this); Buttonjp1.add (selectJB); exitjb = new jbutton ("exit"); exitjb.setFont (New Font ("Zongyi", font.plain, 20)); exitjb.addactionListener (this); Buttonjp1.add (exitJB); selectjp.add (Buttonjp1, borderlayout.south); // página de modificação de informações updatejp = new jpanel (); updatejp.setLayout (new BorderLayout ()); jtabbedpane.addtab ("Modificação de informações do livro", updateJP); bookjp = new jpanel (); Final GridLayout GridLayout = New GridLayout (8, 2); // Defina a distância entre as bordas gridlayout.setvGap (8); gridlayout.sethgap (8); bookjp.setLayout (gridlayout); Isbnjl = new jlabel ("ISBN:"); Isbnjl.setFont (new Font ("宋体", font.plain, 20)); Isbnjl.sethorizontalignment (swingconstants.center); bookjp.add (isbnjl); Isbnjtf = new JTextfield (20); Isbnjtf.addactionListener (this); bookjp.add (isbnjtf); categoryjl = new jlabel ("categoria:"); categoryjl.setFont (nova fonte ("宋体", font.plain, 20)); categoryjl.Sethorizontalignment (swingconstants.center); bookjp.add (categoryjl); // Lista suspensa Lista de Lista <Tooktype> List1 = Booktypedao.SelectBooktype (); Iterator <Booktype> it = list1.iterator (); String ty [] = new String [list1.size ()]; int i = 0; booktypejcb = new JCombobox (); while (it.hasnext ()) {ty [i] = it.next (). getTypeName (); booktypejcb.additem (ty [i]); i ++; } bookjp.add (booktypejcb); bookNamejl = new Jlabel ("Título do livro:"); booknamejl.setFont (New Font ("宋体", font.plain, 20)); booknamejl.SethorizontalAlignment (swingconstants.center); bookjp.add (booknamejl); booknamejtf = new JTextfield (); booknamejtf.setColumns (20); bookjp.add (booknamejtf); autorjl = new jlabel ("autor:"); autorjl.setFont (New Font ("宋体", font.plain, 20)); Authorjl.SethorizontalAlignment (swingconstants.center); bookjp.add (autorjl); autorjtf = new jtextfield (); autorjtf.setColumns (20); bookjp.add (autorjtf); publishjl = new jlabel ("editor:"); publishjl.setFont (New Font ("宋体", font.plain, 20)); publishjl.sethorizontalignment (swingconstants.center); bookjp.add (PublishJL); publishjtf = new JTextfield (); bookjp.add (publishjtf); publishDateJl = new Jlabel ("Data publicada:"); publishdatejl.setfont (new font ("宋体", font.plain, 20)); publishdateJl.SethorizontalIlignment (swingconstants.Center); bookjp.add (PublishDateJL); publishdatejtf = new jtextfield (); publishdatejtf.sethorizontalignment (swingconstants.left); bookjp.add (PublishDatejtf); printTimejl = new jlabel ("Número de impressão:"); printTimejl.setFont (New Font ("宋体", font.plain, 20)); PrintTimeJL.Sethorizontalignment (swingconstants.Center); bookjp.add (printTimeJL); printTimejtf = new JTextField (); bookjp.add (printTimeJTF); unitpricejl = new jlabel ("Preço unitário:"); UnitPriceJl.setFont (New Font ("宋体", font.plain, 20)); UnitPriceJl.SethorizontalAlignment (swingconstants.Center); bookjp.add (UnitPriceJL); UnitPriceJtf = new JTextfield (); bookjp.add (UnitPriceJTF); // Painel do botão // Botão Painel Design ButtonJP2 = new JPanel (); updatejb = new jbutton ("modify"); updatejb.setFont (new Font ("Songyi", font.plain, 20)); updatejb.addactionListener (this); resetJB = new JButton ("Close"); resetjb.setFont (New Font ("Zongyi", font.plain, 20)); resetjb.addactionListener (this); Buttonjp2.add (updatejb); Buttonjp2.add (resetJB); updatejp.add (bookjp, borderlayout.center); updatejp.add (buttonjp2, borderlayout.south); setvisible (true); setDefaultCloseoperation (jframe.exit_on_close); } // Adicione a tabela de consulta ao painel Private Object [] [] getSelect (List <Book> List) {// TODO Método Auto-Generado objeto [] [] objetos = new Object [list.size ()] [title.length]; for (int i = 0; i <list.size (); i ++) {book book = list.get (i); objetos [i] [0] = book.getisbn (); objetos [1] = book.gettypeid (); // objetos de sequência de livros [i] [2] = book.getbookName (); // Nome do livro Objetos [i] [3] = book.getAuthor (); // Objetos do autor [i] [4] = book.getpublish (); // publisher objects [i] objetos [i] [6] = book.getpublishtime (); // número de objetos de impressão [i] [7] = book.getUnitPrice (); // Preço unitário} Return Objects; } public void ActionPerformed (ActionEvent e) {// ToDO Method Auto-Gerated Stub if (e.getSource () == isbnjtf) {string isbn = isbnjtf.getText (); String typename = null; String id = bookdao.selectbookyisbn (isbn) .gettypeid (); typename = booktypedao.SelectById (id); System.out.println (TypeName); booktypejcb.setSelectedItem (typename); booknamejtf.settext (bookdao.SelectBookbyisbn (ISBN) .GetBookName ()); Authorjtf.settext (bookdao.SelectBookbyisbn (ISBN) .GETAUTHOR ()); publishjtf.settext (bookdao.SelectBookbyisbn (ISBN) .getPublish ()); publishdatejtf.settext (bookdao.SelectBookbyisbn (ISBN) .getPublishDate ()); publishdatejtf.settext (bookdao.SelectBookbyisbn (ISBN) .getPublishDate ()+""); printTimejtf.settext (bookdao.SelectBookbyisbn (ISBN) .getPublishTime ()+""); UnitPriceJtf.Settext (bookdao.SelectBookbyisbn (ISBN) .getUnitPrice ()+""); } if (e.getSource () == SElectJB) {// Find Int R = Choicejcb.getSelectedIndex (); if (r == 0) {string name = selectjtf.getText (). TRIM (); // Lista de tipo de tabela linear <Lista> Lista = new ArrayList <Book> (); Livro do livro = bookdao.SelectBookbyisbn (nome); if (book == null) {joptionpane.showMessagedialog (isto, "essa codificação não existe!"); } else {list.add (livro); Objeto [] [] dados = getSelect (list); jtable = new jtable (dados, título); jtable.getColumnModel (). GetColumn (4) .SetPreferredWidth (175); jtable.SetAutoresizEMode (jtable.auto_resize_off); jscrollPane.setViewPortView (jTable); }} if (r == 1) {// Informações de consulta com base no nome do livro Nome da string = selectjtf.getText (). tostring (); List <Book> list = bookdao.SelectBookbyName (nome); // Determine se a tabela linear está vazia se (list == null || list.size () == 0) {JoptionPane.ShowMessAgedialog (this, "o livro não existe!"); } else {object [] [] data = getSelect (list); jtable = new jtable (dados, título); Tianjia (); }} if (r == 2) {// Informações de consulta com base na sequência de livros Nome da sequência = selectjtf.getText (). tostring (); List <Book> list = bookdao.SelectBookbyType (nome); // Determine se a tabela linear está vazia se (list == null || list.size () == 0) {JoptionPane.ShowMessAgedialog (this, "o livro não existe!"); } else {object [] [] data = getSelect (list); jtable = new jtable (dados, título); Tianjia (); }} if (r == 3) {// encontre string de acordo com o nome do autor = selectjtf.getText (). tostring (); // Pesquise por list <Book> List = bookdao.SelectBookbyauthor (nome); // Verifique se a tabela linear está vazia if (list == null || list.size () == 0) {joptionpane.showMessagedialog (this, "Este livro não existe!"); } else {object [] [] data = getSelect (list); jtable = new jtable (dados, título); Tianjia (); }} if (r == 4) {// Pesquise string de acordo com o nome do editor = selectjtf.getText (). tostring (); List <Book> list = bookdao.SelectBookbypublish (nome); if (list == null || list.size () == 0) {JoptionPane.ShowMessagedialog (isto, "Este livro não existe!"); } else {object [] [] data = getSelect (list); jtable = new jtable (dados, título); Tianjia (); }} if (r == 5) {list <Book> list = bookdao.selectbook (); }} if (e.getSource () == updatejb) {string isbn = isbnjtf.getText (). TRIM (); String typename = ((string) booktypejcb.getSelectedItem ()). TRIM (); String id = booktypedao.SelectByTyPename (nome do tipo); String bookName = booknamejtf.getText (); String Author = Authorjtf.getText (); String publish = publishjtf.getText (); String publishdate = publishdatejtf.getText (); SimpledateFormat sdf = new SimpleDateFormat ("AAAA-MM-DD"); Data regdate = null; tente {regdate = sdf.parse (publicHdate); } catch (Exceção E2) {E2.PrintStackTrace (); JoptionPane.showMessagedialog (isto, "Por favor, insira o formato de data correto!"); } if (regDate == null) retornar; int publishTime = Integer.parseint (printTimejtf.getText ()); int UnitPrice = Integer.ParseInt (UnitPriceJtf.getText ()); // encapsula o livro de objetos = novo livro (); book.setIsbn (ISBN); book.setTypeid (ID); book.setbookName (bookName); book.setAuthor (autor); book.setPublish (publish); book.setPublishdate (Regdate); book.setPublishtime (publishtime); book.setUnitPrice (UnitPrice); book.setTypeName (TypeName); int resultado = bookdao.update (livro); List <Book> list2 = new ArrayList <Book> (); List2.Add (livro); // system.out.println (list2); if (resultado == 1) {JoptionPane.ShowMessagedialog (isto, "Modificado com sucesso!"); Bookdao bk = novo bookdao (); List <Book> List = BK.SelectBook (); jtable = new jtable (getSelect (list), título); Tianjia (); } else {JoptionPane.showMessagedialog (isto, "Falha modificada!"); }} if (e.getSource () == resetJB) {dispete (); new mainwindow (); } if (e.getSource () == exitjb) {dispete (); new mainwindow (); }} private void tianjia () {jtable.getColumnModel (). getColumn (4) .SetPreferredWidth (175); jtable.SetAutoresizEMode (jtable.auto_resize_off); jscrollPane.setViewPortView (jTable); } public static void main (string [] args) {new freteleclectAndModify (); }}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.