By GokiSoft.com|
14:53 24/07/2023|
Java Advanced
[Share Code] Bài tập - CRUD Quản lý sách - Kết nối CSDL - Lập trình Java nâng cao - C2209I
Bài tập - CRUD Quản lý sách - Kết nối CSDL - Lập trình Java nâng cao
B1. Thiết kế CSDL
create table book (
id int primary key AUTO_INCREMENT,
book_name varchar(150),
author_name varchar(50),
price float
)
B2. Thực hiện nhập 1-3 bản ghi mẫu
B3. Tạo project
B4. Thêm thư viện vào dự án
B5. Mapping Tables <-> Class Object
#BaseCRUD.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.gokisoft.java2.lesson07;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author teacher
*/
public class BaseCRUD {
static final String DB_NAME = "library";
static final String DB_USERNAME = "root";
static final String DB_PWD = "";
static Connection conn = null;
static PreparedStatement statement = null;
static void connect() {
try {
//Ket noi CSDL -> doc du lieu ra
//B1. Mo ket noi CSDL
conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/" + DB_NAME, DB_USERNAME, DB_PWD);
} catch (SQLException ex) {
Logger.getLogger(com.gokisoft.java2.lesson06.BaseCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
}
static void disconnect() {
//B3. Dong ket noi
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(com.gokisoft.java2.lesson06.BaseCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(com.gokisoft.java2.lesson06.BaseCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
#Book.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.gokisoft.java2.lesson07;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author teacher
*/
public class Book {
int id;
String bookName;
String authorName;
float price;
public Book() {
}
public Book(int id, String bookName, String authorName, float price) {
this.id = id;
this.bookName = bookName;
this.authorName = authorName;
this.price = price;
}
public void readRecord(ResultSet resultSet) {
try {
this.id = resultSet.getInt("id");
this.bookName = resultSet.getString("book_name");
this.authorName = resultSet.getString("author_name");
this.price = resultSet.getFloat("price");
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString() {
return "id=" + id + ", bookName=" + bookName + ", authorName=" + authorName + ", price=" + price;
}
}
#BookCRUD.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.gokisoft.java2.lesson07;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author teacher
*/
public class BookCRUD extends BaseCRUD {
public static List<Book> getList() {
List<Book> dataList = new ArrayList<>();
connect();
String sql = "select * from book";
try {
statement = conn.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Book book = new Book();
book.readRecord(resultSet);
dataList.add(book);
}
} catch (SQLException ex) {
Logger.getLogger(BookCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
disconnect();
return dataList;
}
public static List<Book> search(String s) {
List<Book> dataList = new ArrayList<>();
connect();
String sql = "select * from book where book_name like ? or author_name like ?";
try {
statement = conn.prepareStatement(sql);
statement.setString(1, "%" + s + "%");
statement.setString(2, "%" + s + "%");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Book book = new Book();
book.readRecord(resultSet);
dataList.add(book);
}
} catch (SQLException ex) {
Logger.getLogger(BookCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
disconnect();
return dataList;
}
public static void insert(Book book) {
connect();
String sql = "insert into book(book_name, author_name, price) values (?, ?, ?)";
try {
statement = conn.prepareStatement(sql);
statement.setString(1, book.getBookName());
statement.setString(2, book.getAuthorName());
statement.setFloat(3, book.getPrice());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(BookCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
disconnect();
}
public static void update(Book book) {
connect();
String sql = "update book set book_name = ?, author_name = ?, price= ? where id = ?";
try {
statement = conn.prepareStatement(sql);
statement.setString(1, book.getBookName());
statement.setString(2, book.getAuthorName());
statement.setFloat(3, book.getPrice());
statement.setInt(4, book.getId());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(BookCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
disconnect();
}
public static void delete(int id) {
connect();
String sql = "delete from book where id = ?";
try {
statement = conn.prepareStatement(sql);
statement.setInt(1, id);
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(BookCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
disconnect();
}
public static Book findById(int id) {
Book book = null;
connect();
String sql = "select * from book where id = ?";
try {
statement = conn.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
book = new Book();
book.readRecord(resultSet);
}
} catch (SQLException ex) {
Logger.getLogger(BookCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
disconnect();
return book;
}
}
#BookFrame.form
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
<Property name="title" type="java.lang.String" value="QUAN LY SACH"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" max="-2" attributes="0">
<Component id="jPanel2" max="32767" attributes="0"/>
<Component id="jScrollPane1" max="32767" attributes="0"/>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel2" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jScrollPane1" min="-2" pref="216" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel2">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
<TitledBorder title="NHAP THONG TIN SACH">
<Color PropertyName="color" blue="cc" green="66" red="0" type="rgb"/>
</TitledBorder>
</Border>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="23" max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="jLabel3" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="65" max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Component id="saveBtn" min="-2" max="-2" attributes="0"/>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="deleteBtn" min="-2" max="-2" attributes="0"/>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="searchBtn" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
<Component id="resetBtn" min="-2" max="-2" attributes="0"/>
</Group>
<Component id="txtPrice" max="32767" attributes="0"/>
</Group>
</Group>
<Group type="102" attributes="0">
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="65" max="-2" attributes="0"/>
<Component id="txtBookName" max="32767" attributes="0"/>
</Group>
<Group type="102" alignment="1" attributes="0">
<EmptySpace min="0" pref="0" max="32767" attributes="0"/>
<Component id="jLabel2" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="65" max="-2" attributes="0"/>
<Component id="txtAuthorName" min="-2" pref="340" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="20" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtBookName" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="29" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtAuthorName" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="30" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtPrice" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="saveBtn" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="deleteBtn" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="searchBtn" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="resetBtn" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace pref="15" max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="jLabel1">
<Properties>
<Property name="text" type="java.lang.String" value="TEN SACH:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtBookName">
</Component>
<Component class="javax.swing.JTextField" name="txtAuthorName">
</Component>
<Component class="javax.swing.JLabel" name="jLabel2">
<Properties>
<Property name="text" type="java.lang.String" value="TAC GIA:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtPrice">
</Component>
<Component class="javax.swing.JLabel" name="jLabel3">
<Properties>
<Property name="text" type="java.lang.String" value="GIA TIEN:"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="saveBtn">
<Properties>
<Property name="text" type="java.lang.String" value="LUU"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="saveBtnActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="deleteBtn">
<Properties>
<Property name="text" type="java.lang.String" value="XOA"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="deleteBtnActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="searchBtn">
<Properties>
<Property name="text" type="java.lang.String" value="TIM KIEM"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="searchBtnActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="resetBtn">
<Properties>
<Property name="text" type="java.lang.String" value="XOA FORM"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="resetBtnActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JScrollPane" name="jScrollPane1">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTable" name="bookTable">
<Properties>
<Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
<Table columnCount="4" rowCount="0">
<Column editable="false" title="STT" type="java.lang.Object"/>
<Column editable="false" title="TEN SACH" type="java.lang.Object"/>
<Column editable="false" title="TAC GIA" type="java.lang.Object"/>
<Column editable="false" title="GIA" type="java.lang.Object"/>
</Table>
</Property>
<Property name="columnModel" type="javax.swing.table.TableColumnModel" editor="org.netbeans.modules.form.editors2.TableColumnModelEditor">
<TableColumnModel selectionModel="0">
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
</TableColumnModel>
</Property>
<Property name="tableHeader" type="javax.swing.table.JTableHeader" editor="org.netbeans.modules.form.editors2.JTableHeaderEditor">
<TableHeader reorderingAllowed="true" resizingAllowed="true"/>
</Property>
</Properties>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Form>
#BookFrame.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package com.gokisoft.java2.lesson07;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author teacher
*/
public class BookFrame extends javax.swing.JFrame {
DefaultTableModel tableModel;
List<Book> dataList = new ArrayList<>();
int selectedIndex = -1;
/**
* Creates new form BookFrame
*/
public BookFrame() {
initComponents();
tableModel = (DefaultTableModel) bookTable.getModel();
dataList = BookCRUD.getList();
showDataTable();
bookTable.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
selectedIndex = bookTable.getSelectedRow();
Book book = dataList.get(selectedIndex);
txtBookName.setText(book.getBookName());
txtAuthorName.setText(book.getAuthorName());
txtPrice.setText(book.getPrice() + "");
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
private void showDataTable() {
tableModel.setRowCount(0);
for (Book book : dataList) {
tableModel.addRow(new Object[]{tableModel.getRowCount() + 1, book.getBookName(), book.getAuthorName(), book.getPrice()});
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtBookName = new javax.swing.JTextField();
txtAuthorName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtPrice = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
saveBtn = new javax.swing.JButton();
deleteBtn = new javax.swing.JButton();
searchBtn = new javax.swing.JButton();
resetBtn = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
bookTable = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("QUAN LY SACH");
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "NHAP THONG TIN SACH", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 12), new java.awt.Color(0, 102, 204))); // NOI18N
jLabel1.setText("TEN SACH:");
jLabel2.setText("TAC GIA:");
jLabel3.setText("GIA TIEN:");
saveBtn.setText("LUU");
saveBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveBtnActionPerformed(evt);
}
});
deleteBtn.setText("XOA");
deleteBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteBtnActionPerformed(evt);
}
});
searchBtn.setText("TIM KIEM");
searchBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchBtnActionPerformed(evt);
}
});
resetBtn.setText("XOA FORM");
resetBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(65, 65, 65)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(saveBtn)
.addGap(18, 18, 18)
.addComponent(deleteBtn)
.addGap(18, 18, 18)
.addComponent(searchBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(resetBtn))
.addComponent(txtPrice)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(65, 65, 65)
.addComponent(txtBookName))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(65, 65, 65)
.addComponent(txtAuthorName, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtBookName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtAuthorName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveBtn)
.addComponent(deleteBtn)
.addComponent(searchBtn)
.addComponent(resetBtn))
.addContainerGap(15, Short.MAX_VALUE))
);
bookTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"STT", "TEN SACH", "TAC GIA", "GIA"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(bookTable);
if (bookTable.getColumnModel().getColumnCount() > 0) {
bookTable.getColumnModel().getColumn(0).setResizable(false);
bookTable.getColumnModel().getColumn(1).setResizable(false);
bookTable.getColumnModel().getColumn(2).setResizable(false);
bookTable.getColumnModel().getColumn(3).setResizable(false);
}
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
if (selectedIndex >= 0) {
//update
Book bookUpdate = dataList.get(selectedIndex);
bookUpdate.setBookName(txtBookName.getText());
bookUpdate.setAuthorName(txtAuthorName.getText());
bookUpdate.setPrice(Float.parseFloat(txtPrice.getText()));
BookCRUD.update(bookUpdate);
resetBtnActionPerformed(evt);
} else {
Book book = new Book(
0,
txtBookName.getText(),
txtAuthorName.getText(),
Float.parseFloat(txtPrice.getText())
);
BookCRUD.insert(book);
}
dataList = BookCRUD.getList();
showDataTable();
}//GEN-LAST:event_saveBtnActionPerformed
private void resetBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetBtnActionPerformed
// TODO add your handling code here:
selectedIndex = -1;
txtBookName.setText("");
txtAuthorName.setText("");
txtPrice.setText("");
}//GEN-LAST:event_resetBtnActionPerformed
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteBtnActionPerformed
// TODO add your handling code here:
int selectedIndex = bookTable.getSelectedRow();
if (selectedIndex < 0) {
JOptionPane.showMessageDialog(rootPane, "Vui long chon ban ghi can xoa");
return;
}
int option = JOptionPane.showConfirmDialog(rootPane, "Ban co chac chan muon xoa ban ghi nay khong?");
System.out.println(option);
if (option == 0) {
BookCRUD.delete(dataList.get(selectedIndex).getId());
dataList.remove(selectedIndex);
showDataTable();
}
}//GEN-LAST:event_deleteBtnActionPerformed
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchBtnActionPerformed
// TODO add your handling code here:
String search = JOptionPane.showInputDialog("Nhap tim kiem theo ten hoac tac gia: ");
if(search.isEmpty()) {
dataList = BookCRUD.getList();
} else {
dataList = BookCRUD.search(search);
}
showDataTable();
}//GEN-LAST:event_searchBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(BookFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BookFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BookFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BookFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new BookFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable bookTable;
private javax.swing.JButton deleteBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton resetBtn;
private javax.swing.JButton saveBtn;
private javax.swing.JButton searchBtn;
private javax.swing.JTextField txtAuthorName;
private javax.swing.JTextField txtBookName;
private javax.swing.JTextField txtPrice;
// End of variables declaration//GEN-END:variables
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)