By GokiSoft.com| 15:47 22/03/2021|
Java Advanced

[Share Code] Tìm hiểu về thiết kế Swing Form - Lập trình Java Nâng Cao


#MainFrame.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.java2.lesson06;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.control.DialogPane;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Diep.Tran
 */
public class MainFrame extends javax.swing.JFrame {
    DefaultTableModel tableModel;
    
    List<Book> dataList = new ArrayList<>();
    
    int index = -1;
    
    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        
        tableModel = (DefaultTableModel) tblBook.getModel();
        
        tblBook.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                index = tblBook.getSelectedRow();
                Book book = dataList.get(index);
                
//                System.out.println(book);
                txtTitle.setText(book.getTitle());
                txtNxb.setText(book.getNxb());
                txtPrice.setText(String.valueOf(book.getPrice()));
                txtAuthor.setText(book.getAuthor());
                txtPublishDate.setText(book.getPublishDate());
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        
        dataList = BookModify.getBookList("");
        showData();
    }

    /**
     * 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() {

        jMenu4 = new javax.swing.JMenu();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtTitle = new javax.swing.JTextField();
        txtPrice = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNxb = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtAuthor = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtPublishDate = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnSearch = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblBook = new javax.swing.JTable();

        jMenu4.setText("jMenu4");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("EBook Management");

        jPanel1.setBackground(new java.awt.Color(204, 255, 204));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Book"));

        jLabel1.setText("Title:");

        jLabel2.setText("Price:");

        jLabel3.setText("NXB:");

        jLabel4.setText("Author:");

        jLabel5.setText("Publish Date:");

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(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(23, 23, 23)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addGap(38, 38, 38)
                            .addComponent(txtPublishDate, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtAuthor, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtNxb, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(btnSearch))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSave))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnDelete))
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNxb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(btnSearch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtAuthor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPublishDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(11, 11, 11))
        );

        tblBook.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "No", "Title", "Price", "NXB", "Author", "Publish Date"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblBook);

        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.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, 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:
        System.out.println("Click save ...");
        String title = txtTitle.getText();
        String nxb = txtNxb.getText();
        float price = Float.parseFloat(txtPrice.getText());
        String author = txtAuthor.getText();
        String publishDate = txtPublishDate.getText();
        
        Book book = new Book(title, nxb, author, publishDate, price);
        if(index >= 0) {
            dataList.set(index, book);
            index = -1;
        } else {
            dataList.add(book);
            
            BookModify.insert(book);
        }
        
        System.out.println(book);
        
        resetData();

        showData();
    }//GEN-LAST:event_btnSaveActionPerformed

    void showData() {
        tableModel.setRowCount(0);
        
        for (Book book : dataList) {
            tableModel.addRow(new Object[] {tableModel.getRowCount() + 1, book.getTitle(), book.getPrice(), 
            book.getNxb(), book.getAuthor(), book.getPublishDate()});
        }
    }
    
    void resetData() {
        txtTitle.setText("");
        txtNxb.setText("");
        txtPrice.setText("");
        txtAuthor.setText("");
        txtPublishDate.setText("");
    }
    
    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        if(index >= 0) {
            int option = JOptionPane.showConfirmDialog(rootPane, "Ban co chac chan muon xoa book nay khong?");
            index = -1;
            if(option != 0) {
                return;
            }
            
            dataList.remove(index);
            showData();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Khong co phan tu nao duoc xoa");
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        String search = JOptionPane.showInputDialog("Nhap du lieu can tim");
        if(search.isEmpty()) {
            showData();
            return;
        }
        
        dataList = BookModify.getBookList(search);
        showData();
        /**tableModel.setRowCount(0);
        
        for (Book book : dataList) {
            if(book.getTitle().contains(search)) {
                tableModel.addRow(new Object[] {tableModel.getRowCount() + 1, book.getTitle(), book.getPrice(), 
                book.getNxb(), book.getAuthor(), book.getPublishDate()});
            }
        }*/
    }//GEN-LAST:event_btnSearchActionPerformed

    /**
     * @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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    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.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblBook;
    private javax.swing.JTextField txtAuthor;
    private javax.swing.JTextField txtNxb;
    private javax.swing.JTextField txtPrice;
    private javax.swing.JTextField txtPublishDate;
    private javax.swing.JTextField txtTitle;
    // End of variables declaration//GEN-END:variables
}


#MainFrame.form


<?xml version="1.0" encoding="UTF-8" ?>

<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <NonVisualComponents>
    <Container class="javax.swing.JMenu" name="jMenu4">
      <Properties>
        <Property name="text" type="java.lang.String" value="jMenu4"/>
      </Properties>

      <Layout class="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout">
        <Property name="useNullLayout" type="boolean" value="true"/>
      </Layout>
    </Container>
  </NonVisualComponents>
  <Properties>
    <Property name="defaultCloseOperation" type="int" value="3"/>
    <Property name="title" type="java.lang.String" value="EBook Management"/>
  </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 type="unrelated" max="-2" attributes="0"/>
              <Component id="jScrollPane1" min="-2" pref="181" max="-2" attributes="0"/>
              <EmptySpace max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Container class="javax.swing.JPanel" name="jPanel1">
      <Properties>
        <Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
          <Color blue="cc" green="ff" red="cc" type="rgb"/>
        </Property>
        <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="Input Book"/>
          </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="0" attributes="0">
                      <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
                      <Group type="103" alignment="0" groupAlignment="1" max="-2" attributes="0">
                          <Group type="102" alignment="1" attributes="0">
                              <Component id="jLabel5" min="-2" max="-2" attributes="0"/>
                              <EmptySpace min="-2" pref="38" max="-2" attributes="0"/>
                              <Component id="txtPublishDate" min="-2" pref="283" max="-2" attributes="0"/>
                          </Group>
                          <Group type="102" alignment="1" attributes="0">
                              <Component id="jLabel4" min="-2" max="-2" attributes="0"/>
                              <EmptySpace max="32767" attributes="0"/>
                              <Group type="103" groupAlignment="0" attributes="0">
                                  <Component id="txtPrice" min="-2" pref="283" max="-2" attributes="0"/>
                                  <Component id="txtAuthor" min="-2" pref="283" max="-2" attributes="0"/>
                                  <Component id="txtTitle" alignment="0" min="-2" pref="283" max="-2" attributes="0"/>
                                  <Component id="txtNxb" alignment="0" min="-2" pref="283" max="-2" attributes="0"/>
                              </Group>
                          </Group>
                      </Group>
                      <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace pref="44" max="32767" attributes="0"/>
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Group type="103" groupAlignment="0" max="-2" attributes="0">
                          <Component id="btnDelete" max="32767" attributes="0"/>
                          <Component id="btnSave" max="32767" attributes="0"/>
                      </Group>
                      <Component id="btnSearch" min="-2" max="-2" 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 pref="13" max="32767" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="txtTitle" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="btnSave" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="unrelated" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="1" attributes="0">
                      <Group type="103" alignment="1" groupAlignment="3" attributes="0">
                          <Component id="txtPrice" alignment="3" min="-2" max="-2" attributes="0"/>
                          <Component id="btnDelete" alignment="3" min="-2" max="-2" attributes="0"/>
                      </Group>
                      <Component id="jLabel2" alignment="1" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="txtNxb" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="btnSearch" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="unrelated" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel4" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="txtAuthor" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="unrelated" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="txtPublishDate" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel5" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="11" max="-2" attributes="0"/>
              </Group>
          </Group>
        </DimensionLayout>
      </Layout>
      <SubComponents>
        <Component class="javax.swing.JLabel" name="jLabel1">
          <Properties>
            <Property name="text" type="java.lang.String" value="Title:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="txtTitle">
        </Component>
        <Component class="javax.swing.JTextField" name="txtPrice">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel2">
          <Properties>
            <Property name="text" type="java.lang.String" value="Price:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="txtNxb">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel3">
          <Properties>
            <Property name="text" type="java.lang.String" value="NXB:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="txtAuthor">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel4">
          <Properties>
            <Property name="text" type="java.lang.String" value="Author:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="txtPublishDate">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel5">
          <Properties>
            <Property name="text" type="java.lang.String" value="Publish Date:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JButton" name="btnSave">
          <Properties>
            <Property name="text" type="java.lang.String" value="Save"/>
          </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="Delete"/>
          </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="Search"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnSearchActionPerformed"/>
          </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="6" rowCount="0">
                <Column editable="false" title="No" type="java.lang.Object"/>
                <Column editable="false" title="Title" type="java.lang.Object"/>
                <Column editable="false" title="Price" type="java.lang.Object"/>
                <Column editable="false" title="NXB" type="java.lang.Object"/>
                <Column editable="false" title="Author" type="java.lang.Object"/>
                <Column editable="false" title="Publish Date" 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="true">
                  <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="true">
                  <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="true">
                  <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>


#BookModify.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.java2.lesson06;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class BookModify {
    /**
     * create table book (
	id int primary KEY AUTO_INCREMENT,
            title varchar(100),
            price float,
            nxb varchar(200),
            author varchar(50),
            publish_date varchar(50)
        )
     */
    
    public static List<Book> getBookList(String searching) {
        List<Book> bookList = new ArrayList<>();
        
        Connection conn = null;
        
        try {
            //Mo ket noi toi database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/T2008A", "root", "");
            
            //Query
            String sql = "select * from book";
            if(!searching.isEmpty()) {
                sql += " where title like '%"+searching+"%'";
            }
            
            PreparedStatement statement = conn.prepareStatement(sql);
            
            ResultSet resultSet = statement.executeQuery();
            
            while (resultSet.next()) {                
                Book book = new Book(resultSet.getInt("id"), 
                        resultSet.getString("title"), 
                        resultSet.getString("nxb"), 
                        resultSet.getString("author"), 
                        resultSet.getString("publish_date"), 
                        resultSet.getFloat("price"));
                bookList.add(book);
            }
        } catch (SQLException ex) {
            Logger.getLogger(BookModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(conn != null) {
                try {
                    //Dong ket noi toi database
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(BookModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        return bookList;
    }
    
    //B2. Tai thu jdbc driver
    public static void insert(Book book) {
        Connection conn = null;
        
        try {
            //Mo ket noi toi database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/T2008A", "root", "");
            
            //Query
            PreparedStatement statement = conn.prepareStatement("insert into book(title, price, nxb, author, publish_date) values (?, ?, ?, ?, ?)");
            statement.setString(1, book.getTitle());
            statement.setString(2, String.valueOf(book.getPrice()));
            statement.setString(3, book.getNxb());
            statement.setString(4, book.getAuthor());
            statement.setString(5, book.getPublishDate());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(BookModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(conn != null) {
                try {
                    //Dong ket noi toi database
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(BookModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


#Book.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.java2.lesson06;

/**
 *
 * @author Diep.Tran
 */
public class Book {
    String title, nxb, author, publishDate;
    float price;
    int id;

    public Book() {
    }

    public Book(int id, String title, String nxb, String author, String publishDate, float price) {
        this.title = title;
        this.nxb = nxb;
        this.author = author;
        this.publishDate = publishDate;
        this.price = price;
        this.id = id;
    }

    
    
    public Book(String title, String nxb, String author, String publishDate, float price) {
        this.title = title;
        this.nxb = nxb;
        this.author = author;
        this.publishDate = publishDate;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getNxb() {
        return nxb;
    }

    public void setNxb(String nxb) {
        this.nxb = nxb;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(String publishDate) {
        this.publishDate = publishDate;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" + "title=" + title + ", nxb=" + nxb + ", author=" + author + ", publishDate=" + publishDate + ", price=" + price + '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    
}


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)