By GokiSoft.com|
19:55 14/06/2024|
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 - C2307L
Bài tập - CRUD Quản lý sách - Kết nối CSDL - Lập trình Java nâng cao
#BaseEntity.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.lesson06;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author teacher
* @param <T>
*/
public abstract class BaseEntity<T> {
final String HOST = "jdbc:mysql://localhost:3308/library";
final String USERNAME = "root";
final String PASSWORD = "";
Connection con = null;
PreparedStatement statement = null;
public void openConnection() {
try {
//KET NOI CSDL
//B1. Tao ket noi toi CSDL
con = DriverManager.getConnection(HOST, USERNAME, PASSWORD);
} catch (SQLException ex) {
Logger.getLogger(BaseEntity.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void closeConnection() {
//B3. Dong ket noi toi CSDL
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(BaseEntity.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(BaseEntity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public abstract List<T> findAll();
public abstract void insert(T item);
public abstract void update(T item);
public abstract void delete(T item);
public abstract T findById(T item);
}
#Books.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.lesson06;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author teacher
*/
public class Books {
int id;
String bookName;
float price;
String authorName;
public Books() {
}
public Books(int id) {
this.id = id;
}
public Books(int id, String bookName, float price, String authorName) {
this.id = id;
this.bookName = bookName;
this.price = price;
this.authorName = authorName;
}
public Books(ResultSet resultSet) {
try {
this.id = resultSet.getInt("id");
this.bookName = resultSet.getString("book_name");
this.price = resultSet.getFloat("price");
this.authorName = resultSet.getString("author_name");
} catch (SQLException ex) {
Logger.getLogger(Books.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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
@Override
public String toString() {
return "id=" + id + ", bookName=" + bookName + ", price=" + price + ", authorName=" + authorName;
}
public void display() {
System.out.println(this);
}
public void input() {
Scanner scan = new Scanner(System.in);
System.out.println("Nhap sach: ");
bookName = scan.nextLine();
System.out.println("Nhap gia: ");
price = Float.parseFloat(scan.nextLine());
System.out.println("Nhap ten tac gia: ");
authorName = scan.nextLine();
}
}
#BooksEntity.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.lesson06;
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 BooksEntity extends BaseEntity<Books>{
private static BooksEntity instance = null;
private BooksEntity() {
}
public synchronized static BooksEntity getInstance() {
if(instance == null) {
instance = new BooksEntity();
}
return instance;
}
@Override
public List<Books> findAll() {
List<Books> dataList = new ArrayList<>();
openConnection();
String sql = "select * from books";
try {
statement = con.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
Books book = new Books(resultSet);
dataList.add(book);
}
} catch (SQLException ex) {
Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
}
closeConnection();
return dataList;
}
@Override
public void insert(Books item) {
openConnection();
String sql = "insert into books(book_name, price, author_name) values (?, ?, ?)";
try {
statement = con.prepareStatement(sql);
statement.setString(1, item.getBookName());
statement.setFloat(2, item.getPrice());
statement.setString(3, item.getAuthorName());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
}
closeConnection();
}
@Override
public void update(Books item) {
openConnection();
String sql = "update books set book_name=?,price=?,author_name=? where id=?";
try {
statement = con.prepareStatement(sql);
statement.setString(1, item.getBookName());
statement.setFloat(2, item.getPrice());
statement.setString(3, item.getAuthorName());
statement.setInt(4, item.getId());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
}
closeConnection();
}
@Override
public void delete(Books item) {
openConnection();
String sql = "delete from books where id=?";
try {
statement = con.prepareStatement(sql);
statement.setInt(1, item.getId());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
}
closeConnection();
}
@Override
public Books findById(Books item) {
Books itemFind = null;
openConnection();
String sql = "select * from books where id = ?";
try {
statement = con.prepareStatement(sql);
statement.setInt(1, item.getId());
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
itemFind = new Books(resultSet);
break;
}
} catch (SQLException ex) {
Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
}
closeConnection();
return itemFind;
}
}
#Main.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.lesson06;
import java.util.List;
import java.util.Scanner;
/**
*
* @author teacher
*/
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choose;
do {
showMenu();
choose = Integer.parseInt(scan.nextLine());
switch (choose) {
case 1 -> input();
case 2 -> edit();
case 3 -> remove();
case 4 -> display();
case 5 -> System.out.println("Thoat!!!");
default -> System.out.println("Nhap sai!!!");
}
} while (choose != 5);
}
static void showMenu() {
System.out.println("1. Them");
System.out.println("2. Sua");
System.out.println("3. Xoa");
System.out.println("4. Hien thi");
System.out.println("5. Thoat");
System.out.println("Chon: ");
}
private static void input() {
System.out.println("=== NHAP ===");
Books book = new Books();
book.input();
BooksEntity.getInstance().insert(book);
}
private static void edit() {
System.out.println("=== XOA ===");
Scanner scan = new Scanner(System.in);
System.out.println("Nhap ID can sua: ");
int id = Integer.parseInt(scan.nextLine());
Books book = new Books(id);
book.input();
BooksEntity.getInstance().update(book);
}
private static void remove() {
System.out.println("=== XOA ===");
Scanner scan = new Scanner(System.in);
System.out.println("Nhap ID can xoa: ");
int id = Integer.parseInt(scan.nextLine());
BooksEntity.getInstance().delete(new Books(id));
}
private static void display() {
System.out.println("=== HIEN THI ===");
List<Books> dataList = BooksEntity.getInstance().findAll();
for (Books book : dataList) {
book.display();
}
}
}
#readme.txt
1) Tao CSDL
create database library;
create table books (
id int primary key auto_increment,
book_name varchar(150),
price float,
author_name varchar(150)
)
#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"/>
</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" attributes="0">
<Component id="jPanel1" max="32767" attributes="0"/>
<Component id="jScrollPane1" max="32767" attributes="0"/>
</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 max="-2" attributes="0"/>
<Component id="jPanel1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jScrollPane1" min="-2" pref="201" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<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"/>
</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="19" max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" max="-2" attributes="0">
<Group type="102" attributes="0">
<Component id="jLabel3" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
<Component id="txtAuthorName" min="-2" pref="264" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<Component id="jLabel2" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
<Component id="txtPrice" min="-2" pref="264" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="55" max="-2" attributes="0"/>
<Component id="txtBookName" min="-2" pref="264" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" max="-2" attributes="0">
<Group type="102" attributes="0">
<Component id="btnSave" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnDelete" min="-2" max="-2" attributes="0"/>
</Group>
<Component id="btnSearch" max="32767" attributes="0"/>
<Component id="btnClear" alignment="0" max="32767" attributes="0"/>
</Group>
<EmptySpace pref="11" 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 min="-2" pref="13" 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"/>
<Component id="btnSave" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnDelete" 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="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtPrice" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnSearch" 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="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtAuthorName" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnClear" 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.JLabel" name="jLabel2">
<Properties>
<Property name="text" type="java.lang.String" value="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="Tac gia:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtAuthorName">
</Component>
<Component class="javax.swing.JButton" name="btnSave">
<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="btnSaveActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnDelete">
<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="btnDeleteActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnSearch">
<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="btnSearchActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnClear">
<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="btnClearActionPerformed"/>
</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="tblBook">
<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="Gia" type="java.lang.Object"/>
<Column editable="false" title="Tac 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="true">
<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="true">
<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.lesson06;
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 final class BookFrame extends javax.swing.JFrame {
DefaultTableModel tableModel;
List<Books> dataList = new ArrayList<>();
int currIndex = -1;
/**
* Creates new form BookFrame
*/
public BookFrame() {
initComponents();
tableModel = (DefaultTableModel) tblBook.getModel();
showAllData();
tblBook.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
currIndex = tblBook.getSelectedRow();
Books book = dataList.get(currIndex);
txtBookName.setText(book.getBookName());
txtPrice.setText(book.getPrice()+"");
txtAuthorName.setText(book.getAuthorName());
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
void showAllData() {
dataList = BooksEntity.getInstance().findAll();
tableModel.setRowCount(0);
for (Books books : dataList) {
tableModel.addRow(new Object[] {
tableModel.getRowCount() + 1,
books.getBookName(),
books.getPrice(),
books.getAuthorName()
});
}
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtBookName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtPrice = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtAuthorName = new javax.swing.JTextField();
btnSave = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
btnSearch = new javax.swing.JButton();
btnClear = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblBook = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("NHAP THONG TIN SACH"));
jLabel1.setText("Ten sach:");
jLabel2.setText("Gia:");
jLabel3.setText("Tac gia:");
btnSave.setText("Luu");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnDelete.setText("Xoa");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
btnSearch.setText("TIM KIEM");
btnSearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSearchActionPerformed(evt);
}
});
btnClear.setText("XOA FORM");
btnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnClearActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtAuthorName, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(55, 55, 55)
.addComponent(txtBookName, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnSave)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDelete))
.addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(11, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(13, 13, 13)
.addGroup(jPanel1Layout.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)
.addComponent(btnSave)
.addComponent(btnDelete))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSearch))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtAuthorName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnClear))
.addContainerGap(15, Short.MAX_VALUE))
);
tblBook.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"STT", "Ten Sach", "Gia", "Tac Gia"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblBook);
if (tblBook.getColumnModel().getColumnCount() > 0) {
tblBook.getColumnModel().getColumn(0).setResizable(false);
tblBook.getColumnModel().getColumn(2).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)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, 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, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
// TODO add your handling code here:
String bookName = txtBookName.getText();
float price = Float.parseFloat(txtPrice.getText());
String authorName = txtAuthorName.getText();
if(currIndex >= 0) {
Books book = dataList.get(currIndex);
book.setBookName(bookName);
book.setPrice(price);
book.setAuthorName(authorName);
BooksEntity.getInstance().update(book);
} else {
Books book = new Books(0, bookName, price, authorName);
BooksEntity.getInstance().insert(book);
}
showAllData();
btnClearActionPerformed(evt);
}//GEN-LAST:event_btnSaveActionPerformed
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
// TODO add your handling code here:
int index = tblBook.getSelectedRow();
if(index < 0) {
JOptionPane.showMessageDialog(rootPane, "Chon ban ghi can xoa");
return;
}
Books book = dataList.get(index);
BooksEntity.getInstance().delete(book);
showAllData();
}//GEN-LAST:event_btnDeleteActionPerformed
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnSearchActionPerformed
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
// TODO add your handling code here:
txtBookName.setText("");
txtPrice.setText("");
txtAuthorName.setText("");
currIndex = -1;
}//GEN-LAST:event_btnClearActionPerformed
/**
* @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.JButton btnClear;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnSave;
private javax.swing.JButton btnSearch;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblBook;
private javax.swing.JTextField txtAuthorName;
private javax.swing.JTextField txtBookName;
private javax.swing.JTextField txtPrice;
// End of variables declaration//GEN-END:variables
}
Tags: